0

I set a content_script "run_at": "document_end". It modifies the page, but I want to have a user setting that determines whether the modification should be done or not.

At first, I tried chrome.storage.sync.get. It was declared at the beginning of the script and the code that begines the modification was declared at the end of the script. (In the middle, there are functions and variables.) But when I tested it, the sync.get callback was called after the modification code. That is, I get the output like:

Using the value.
Read value from storage.

if the code is like the one at the bottom. I thought it was due to the latency from getting data from a remote Google server, but when I changed sync to local, the result was the same. How can I read the setting before doing the actual work?

  1. Should I begin working when the storage.X.get returns, i.e., in its call back? But that would mean unnecessary delay before starting the work. If this is the only way, I will use this.
  2. Isn't there some kind of way to make storage.X.get faster, like caching?
  3. If storage.X.get does not support caching, how can I cache it myself? The modification is only done once for page loading and the content script gets recreated at each page loading. Is there a way to keep a variable across page loadings in the content script, sort of like a static variable?

.

var modify = true;

//initial read
chrome.storage.local.get("modifySetting",
     function(data)
     {
        console.log("Read value from storage");
        if("modifySetting" in data)
        {
            modifySetting = data["modifySetting"];
        }
     }
);

... lots of functions and variables ...

console.log("Using the value.");
if(modify)
{
    doModification();
}
Damn Vegetables
  • 11,484
  • 13
  • 80
  • 135
  • All `chrome` API callbacks are asynchronous so you need to use the value inside the callback. See [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/q/23667086) – wOxxOm Aug 06 '20 at 03:33
  • @wOxxOm So, is chrome.storage.x.get/set is the only way to share a variable between page refreshes for a content_script? There is no such thing that I can share a variable between page refreshes for the same content_script? – Damn Vegetables Aug 06 '20 at 03:55
  • Although isolated, content scripts are added to the web page environment so when the page is navigated all its scripts (including the content scripts) are destroyed. FWIW, in your case I would switch to chrome.declarativeContent API with RequestContentScript action to register/unregister the content script. The documentation says the action is experimental but it actually works. – wOxxOm Aug 06 '20 at 04:10

0 Answers0