Use the chrome.storage
module
to store, retrieve, and track changes to user data.
This API has been optimized
to meet the specific storage needs of extensions.
It provides the same storage capabilities as the
localStorage API
with the following key differences:
storage.sync
).localStorage API
stores data in strings).You must declare the "storage" permission in the extension manifest to use the storage API. For example:
{ "name": "My extension", ... "permissions": [ "storage" ], ... }
To store user data for your extension,
you can use either
storage.sync
or
storage.local
.
When using storage.sync
,
the stored data will automatically be persisted
across any Chrome browser that the user is logged into
provided the user's has sync enabled.
When Chrome's offline,
Chrome stores the data locally.
The next time the browser is online,
Chrome syncs the data.
Even if a user disables syncing,
storage.sync
will still work.
In this case, it will behave identically
to storage.local
.
Confidential user information should not be stored! The storage area isn't encrypted.
Storage space is limited to:
The throttling limit for modification calls to the Storage API is 1000 operations per hour.
Storing user data is
as simple as calling
set()
.
The following example checks for
CSS code saved by a user on a form,
and if found,
stores it.
function saveChanges() { // Get the current CSS snippet from the form. var cssCode = textarea.value; // Check that there's some code there. if (!cssCode) { message('Error: No CSS specified'); return; } // Save it using the Chrome extension storage API. chrome.experimental.storage.sync.set({'css': cssCode}, function() { // Notify that we saved. message('Settings saved'); }); }
If you're interested in tracking changes made
to a data object,
you can add a listener
to its onChanged
event.
Whenever anything changes in storage,
that event fires.
Here's sample code
to listen for saved css changes:
chrome.storage.onChanged.addListener(saveChanges); saveChanges();
You can find examples that use this API on the Samples page.