Hi!
I’ve been looking around for a while, but I don’t seem to find any example or documentation to do what I would like to be able to… Any help would be appreciated.
Basically, I’m writing an extension that will add a button on some pages. The core is working fine . However, what I would like to do, is to keep my configuration on my site and have the extension retrieve it on startup, or on the tab loading. I’ve been trying a number of things, including a background script, but I don’t seem to be able to get things to work as I would like…
In my current content script, I have basically this:
var cfg = null;
fetchConfig();
console.log('DONE');
function fetchConfig() {
let gettingItem = browser.storage.local.get("config");
gettingItem.then(onGot, onError);
}
function onGot(item) {
console.log('in onGot');
console.log(JSON.stringify(item));
if(JSON.stringify(item) != "{}"){
// We have something in the local storage: load cfg
console.log('we are loading cfg');
cfg = item;
}else{
if(cfg == null){
console.log('onGot - cfg is null');
let req = new Request('https://example.com/getconfig.php', {
method: 'GET',
headers: { 'Accept': 'application/json' },
redirect: 'follow',
referrer: 'client'
});
console.log('starting fetch');
window.fetch(req).then(function(response) {
console.log('in fetch');
// .json returns another promise
return response.json();
}).then(function(config) {
console.log('Setting storage');
browser.storage.local.set({config: config});
cfg = config;
console.log('REGISTERED!');
}).catch(error => { console.log(error); });
console.log('onGot finished');
} // cfg is null?
}
console.log('returning ongot');
}
function onError(error) {
console.log(`Error (onError): ${error}`);
cfg = null;
}
The idea is to have a global variable (cfg) on the page initialized with the storage.local key “config”. If this storage key doesn’t exist (the first time the add-on is invoked), then I would download the config from my host and store it in storage.set. This will mean that the next time I load a page, I won’t have to fetch the resource from the server and will just use the item in storage.local.
I’m sure there’s something wrong, as this doesn’t seem to work and would like to understand if I’m doing the right thing, if there are better/recommended ways to use this approach, or if this is completely wrong.
These are the settings in manifest.json:
"permissions": [
"<all_urls>",
"webRequest",
"storage"
]
Many thanks in advance!