I want to be able to store data on background (on my extension) so I can access this data between multiple domains.
Where\'s what I\'m doing:
content-scr
This 2012 question was brought up for an up-to-date answer. Well, then..
Right now the proper answer would be to use chrome.storage API. It's an API accessible for both extension pages and content scripts, and it provides asynchronous storage. It requires "storage"
permission, but this permission generates no warnings.
// Setting
chrome.storage.local.set({key: data}, function() {
if(chrome.runtime.lastError) {
console.error(
"Error setting " + key + " to " + JSON.stringify(data) +
": " + chrome.runtime.lastError.message
);
}
});
// Getting
chrome.storage.local.get("key", function(data) {
// Do something with data.key
});
See also the Examples part of the documentation.
Note that in either case (this approach, or messaging-the-background approach) you can't make a function getData
that returns a result, since the call is asynchronous.
Some tips and tricks:
You can set or get multiple values at once by passing an object or an array as a query. You can read all values by passing the null
query.
You can provide a default value for the get()
operation in case there's no value stored for the key, by passing a query like {key: defaultValue}
You can be notified of all changes to the storage with chrome.storage.onChanged
event.
chrome.storage.local
obeys "unlimitedStorage"
permission.
chrome.storage.sync
will propagate the value to all profiles signed in to the same Google Account, if Chrome Sync is enabled for extensions. However, keep quotas in mind.
If you absolutely need synchronous access, you can fake it with a local cache backed by chrome.storage
. There are, however, limitations: while in a synchronous code block, your cache won't be updated with changes from other pages, and you need to read the values once asynchronously to populate the cache.