How to access localStorage in extension background page?

好久不见. 提交于 2020-01-15 12:20:40

问题


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"); 
    }
  }
});

回答1:


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.



来源:https://stackoverflow.com/questions/23836198/how-to-access-localstorage-in-extension-background-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!