Search code examples
javascripthtmlgoogle-chrome-extensioncontent-script

How to access localStorage in extension background page?


I have a chrome extension that sets a string value in JavaScript localStorage in a content script. I have tested that it is being set by grabbing it and displaying it. While on the same page after it has loaded I can still access the stored string in the javascript console. If I go to any other tabs js console or when I try to access it in my other extensions background page(After the browser action has been clicked) it is returning null.

extension 1 contentscript.js

embeded.addEventListener
(
 "message",
 function(message)
 {
  localStorage.setItem("pdf", message.data);
  loadPDF(message.data);
 },
 false
);

extension 2 background.js

chrome.browserAction.onClicked.addListener(function(tab) {
  if (tab.url.substr(tab.url.length - 4) === ".pdf")
  {    
    if (localStorage.getItem("pdf") !== null)
    {
      alert("boomy"); 
    }
  }
});

Solution

  • localStorage is shared among extension pages (background, options, popup), but not content scripts. And most certainly not shared between 2 extensions!

    You have two-and-a-half options. With 2 separate extensions, only one option.


    Option one: rely on messaging.

    When you need to pass some value between background and content script, you can do so with messaging. Works especially well if you only need to pass it in one direction.

    contentscript.js:

    embeded.addEventListener(
      "message",
      function(message)
      {
        chrome.runtime.sendMessage(extensionTwoId, {pdf: message.data});
        loadPDF(message.data);
      },
      false
    );
    

    background.js:

    chrome.runtime.onMessageExternal.addListener(
      function(message, sender, sendResponse) {
        if(sender.id !== extenstionOneId) return;
        if(message.pdf) localStorage.setItem("pdf", message.pdf);
      }
    );
    
    /* ... */
    

    Option two: chrome.storage. Not applicable between 2 extensions.