views:

37

answers:

1

So, i have an options page where the user can define certain options and it saves it in localstorage: options.html

Now, i also have a content script that needs to get the options that were defined on options.html page, but when i try to access localStorage from content script, it doesn't return the value from options page.

How do i make my content script get values from localStorage from options page or even the background page.

+1  A: 

Content scripts run in the context of webpages, not extension pages. Therefore, if your accessing localStorage from your contentscript, it will be the storage from that webpage, not the extension page storage.

Now, to let your content script to read your extension storage (where you set them from your options page), you need to use extension message passing.

The first thing you do is tell your content script to send a request to your extension to fetch some data, and that data can be your extension localStorage:

contentscript.js

chrome.extension.sendRequest({method: "getStatus"}, function(response) {
  console.log(response.status);
});

background.html

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
    if (request.method == "getStatus")
      sendResponse({status: localStorage['status']});
    else
      sendResponse({}); // snub them.
});

You can do an API around that to get generic localStorage data to your content script, or perhaps, get the whole localStorage array.

I hope that helped solve your problem.

Mohamed Mansour