Search code examples
google-chromegoogle-chrome-extensionpopuplocal-storagebrowser-action

Modify local storage via popup, and use stored values in contentscript


I'm trying my hand at creating a chrome extension, but am running into a wall.

I want to be able to use the browser-action popup to write/modify values into local storage (extension storage).

Then, I want to use the stored values in a content script.

From what I've read, it looks like I need a background file? but I'm not sure.

Some coded examples would be extremely appreciated!

Thanks for your help!


Solution

  • You can avoid using a background page as a proxy if you use chrome.storage API. It's a storage solution that is available from Content Scripts directly.

    Here is a comparison between it and localStorage in the context of Chrome extensions.


    An important thing to note is that it's asynchronous, making code slightly more complicated than using localStorage:

    /* ... */
    chrome.storage.local.get('key', function(value){
      // You can use value here
    });
    // But not here, as it will execute before the callback
    /* ... */
    

    But to be fair, if you go with the background being the proxy for data, message passing is still asynchronous.


    One can argue that once the data is passed, localStorage works as a synchronous cache.

    But that localStorage object is shared with the web page, which is insecure, and nobody stops you from having your own synchronous storage cache, initialized once with chrome.storage.local.get(null, /*...*/) and kept up to date with a chrome.storage.onChanged listener.