0

Using localStorage, I try to store users configs, and it works well.

// in options_page
localStorage.setItem('myKey',someVal);

But it's difficult to read this configs from content_scripts (´・ω・`)

localStorage.getItem('myKey');
// because different 'window' scope

I'm making it by using runtime.sendMessage

// in content_scripts
chrome.runtime.sendMessage(null, {purpose:'getConfig',configKey:'myKey'},
    function(confHere){
        // some action
    }
);

I think it's complex!! (and using 'chrome.storage' requires permission, ugly) Is there any way to read configs from content_scripts of Chrome extension?

otiai10
  • 4,289
  • 5
  • 38
  • 50

1 Answers1

0

Content scripts run within the context of the pages that they are sharing the DOM with and not the extension. So, a content script trying to read from localStorage will read from the localStorage of the page, and not the extension.

The way you proposed is correct and as far as I know the best way to access setting info in your content script. So, when the content script is created send a message to the background to get the settings (as you have done) and then in background add a listener that will return those settings. It's not super clean ... but it is intuitive when you think of what content scripts are supposed to be (and not be).

Here is a SO answer that outlines exactly what you need (although from the sounds of it you already know what must be done :)) Also, if you are interested the content script page of the extension docs has some good (and short) videos at the bottom that helped me understand the ideas behind what content scripts should be able to do.

Community
  • 1
  • 1
berrberr
  • 1,914
  • 11
  • 16