Chrome extension: store data on background

后端 未结 3 696
情书的邮戳
情书的邮戳 2021-02-04 19:21

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

3条回答
  •  执念已碎
    2021-02-04 19:47

    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:

    1. 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.

    2. 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}

    3. You can be notified of all changes to the storage with chrome.storage.onChanged event.

    4. chrome.storage.local obeys "unlimitedStorage" permission.

    5. 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.

    6. 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.

提交回复
热议问题