chrome.storage
- Description
Use the
chrome.storage
API to store, retrieve, and track changes to user data. - Permissions
storage
Overview #
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:
- User data can be automatically synced with Chrome sync (using
storage.sync
). - Your extension's content scripts can directly access user data without the need for a background page.
- A user's extension settings can be persisted even when using split incognito behavior.
- It's asynchronous with bulk read and write operations, and therefore faster than the blocking and serial
localStorage API
. - User data can be stored as objects (the
localStorage API
stores data in strings). - Enterprise policies configured by the administrator for the extension can be read (using
storage.managed
with a schema).
Manifest #
You must declare the "storage" permission in the extension manifest to use the storage API. For example:
{
"name": "My extension",
...
"permissions": [
"storage"
],
...
}
Usage #
To store user data for your extension, you can use either storage.sync
:
chrome.storage.sync.set({key: value}, function() {
console.log('Value is set to ' + value);
});
chrome.storage.sync.get(['key'], function(result) {
console.log('Value currently is ' + result.key);
});
or storage.local
:
chrome.storage.local.set({key: value}, function() {
console.log('Value is set to ' + value);
});
chrome.storage.local.get(['key'], function(result) {
console.log('Value currently is ' + result.key);
});
When using storage.sync
, the stored data will automatically be synced to any Chrome browser that the user is logged into, provided the user has sync enabled.
When Chrome is 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.
The storage.managed
storage is read-only.
Storage and throttling limits #
chrome.storage
is not a big truck. It's a series of tubes. And if you don't understand, those tubes can be filled, and if they are filled when you put your message in, it gets in line, and it's going to be delayed by anyone that puts into that tube enormous amounts of material.
For details on the current limits of the storage API, and what happens when those limits are exceeded, please see the quota information for sync and local.
Examples #
The following example checks for CSS code saved by a user on a form, and if found, stores it.
function saveChanges() {
// Get a value saved in a form.
var theValue = textarea.value;
// Check that there's some code there.
if (!theValue) {
message('Error: No value specified');
return;
}
// Save it using the Chrome extension storage API.
chrome.storage.sync.set({'value': theValue}, 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 changes:
chrome.storage.onChanged.addListener(function(changes, namespace) {
for (var key in changes) {
var storageChange = changes[key];
console.log('Storage key "%s" in namespace "%s" changed. ' +
'Old value was "%s", new value is "%s".',
key,
namespace,
storageChange.oldValue,
storageChange.newValue);
}
});
Summary
- Types
- Properties
- Events
Types
StorageArea
Properties
- onChangedevents.Event<function>
Fired when one or more items change.
Add a listener like this:
onChanged.addListener(listener)
- listenerfunction
The listener parameter should be a function that looks like this:
(changes: object) => {...}
- changesobject
Object mapping each key that changed to its corresponding
StorageChange
for that item.
- clearfunction
Removes all items from storage.
The clear function looks like this:
clear(callback: function) => {...}
- callbackfunction
Callback on success, or on failure (in which case
runtime.lastError
will be set).The callback parameter should be a function that looks like this:
() => {...}
- getfunction
Gets one or more items from storage.
The get function looks like this:
get(keys?: string | string[] | object, callback: function) => {...}
- keysstring | string[] | object optional
A single key to get, list of keys to get, or a dictionary specifying default values (see description of the object). An empty list or object will return an empty result object. Pass in
null
to get the entire contents of storage. - callbackfunction
Callback with storage items, or on failure (in which case
runtime.lastError
will be set).The callback parameter should be a function that looks like this:
(items: object) => {...}
- itemsobject
Object with items in their key-value mappings.
- getBytesInUsefunction
Gets the amount of space (in bytes) being used by one or more items.
The getBytesInUse function looks like this:
getBytesInUse(keys?: string | string[], callback: function) => {...}
- keysstring | string[] optional
A single key or list of keys to get the total usage for. An empty list will return 0. Pass in
null
to get the total usage of all of storage. - callbackfunction
Callback with the amount of space being used by storage, or on failure (in which case
runtime.lastError
will be set).The callback parameter should be a function that looks like this:
(bytesInUse: number) => {...}
- bytesInUsenumber
Amount of space being used in storage, in bytes.
- removefunction
Removes one or more items from storage.
The remove function looks like this:
remove(keys: string | string[], callback: function) => {...}
- keysstring | string[]
A single key or a list of keys for items to remove.
- callbackfunction
Callback on success, or on failure (in which case
runtime.lastError
will be set).The callback parameter should be a function that looks like this:
() => {...}
- setfunction
Sets multiple items.
The set function looks like this:
set(items: object, callback: function) => {...}
- itemsobject
An object which gives each key/value pair to update storage with. Any other key/value pairs in storage will not be affected.
Primitive values such as numbers will serialize as expected. Values with a
typeof
"object"
and"function"
will typically serialize to{}
, with the exception ofArray
(serializes as expected),Date
, andRegex
(serialize using theirString
representation). - callbackfunction
Callback on success, or on failure (in which case
runtime.lastError
will be set).The callback parameter should be a function that looks like this:
() => {...}
StorageChange
Properties
- newValueany optional
The new value of the item, if there is a new value.
- oldValueany optional
The old value of the item, if there was an old value.
Properties
local
Items in the local
storage area are local to each machine.
Type
Properties
- QUOTA_BYTESnumber 5242880
The maximum amount (in bytes) of data that can be stored in local storage, as measured by the JSON stringification of every value plus every key's length. This value will be ignored if the extension has the
unlimitedStorage
permission. Updates that would cause this limit to be exceeded fail immediately and setruntime.lastError
.
managed
Items in the managed
storage area are set by the domain administrator, and are read-only for the extension; trying to modify this namespace results in an error.
Type
sync
Items in the sync
storage area are synced using Chrome Sync.
Type
Properties
- MAX_ITEMSnumber 512
The maximum number of items that can be stored in sync storage. Updates that would cause this limit to be exceeded will fail immediately and set
runtime.lastError
. - MAX_SUSTAINED_WRITE_OPERATIONS_PER_MINUTEnumber 1000000
Deprecated. The storage.sync API no longer has a sustained write operation quota.
- MAX_WRITE_OPERATIONS_PER_HOURnumber 1800
The maximum number of
set
,remove
, orclear
operations that can be performed each hour. This is 1 every 2 seconds, a lower ceiling than the short term higher writes-per-minute limit.Updates that would cause this limit to be exceeded fail immediately and set
runtime.lastError
. - MAX_WRITE_OPERATIONS_PER_MINUTEnumber 120
The maximum number of
set
,remove
, orclear
operations that can be performed each minute. This is 2 per second, providing higher throughput than writes-per-hour over a shorter period of time.Updates that would cause this limit to be exceeded fail immediately and set
runtime.lastError
. - QUOTA_BYTESnumber 102400
The maximum total amount (in bytes) of data that can be stored in sync storage, as measured by the JSON stringification of every value plus every key's length. Updates that would cause this limit to be exceeded fail immediately and set
runtime.lastError
. - QUOTA_BYTES_PER_ITEMnumber 8192
The maximum size (in bytes) of each individual item in sync storage, as measured by the JSON stringification of its value plus its key length. Updates containing items larger than this limit will fail immediately and set
runtime.lastError
.
Events
onChanged
chrome.storage.onChanged.addListener(listener: function)
Fired when one or more items change.
Event
- listenerfunction
The listener parameter should be a function that looks like this:
(changes: object, areaName: string) => {...}
- changesobject
Object mapping each key that changed to its corresponding
StorageChange
for that item. - areaNamestring
The name of the storage area (
"sync"
,"local"
or"managed"
) the changes are for.