This is the last step in building my extension and I am seriously stuck. I have researched chrome.local.storage, but can't get it to work.
I have the following in mypopup.js
let a = document.getElementById("option01");
a.addEventListener("click", async () => {
let [tab] = await chrome.tabs.query({
active: true,
currentWindow: true
});
a.setAttribute('aria-checked', a.getAttribute('aria-checked') === 'true' ? 'false' : 'true');
if (a.getAttribute('aria-checked') === 'true') {
try {
await chrome.scripting.insertCSS({
target: {
tabId: tab.id,
},
files: ["css/option01.css"],
});
} catch (err) {
console.error(`failed to insert roles CSS: ${err}`);
}
} else if (a.getAttribute('aria-checked') === 'false') {
try {
await chrome.scripting.removeCSS({
target: {
tabId: tab.id,
},
files: ["css/option01.css"],
});
} catch (err) {
console.error(`failed to remove roles CSS: ${err}`);
}
}
});
I have tried all different variations of set and get for chrome storage, and although I understand the concept, making it work as I want has me pulling my hair out. I'd really appreciate some help.
This is as far as I got trying to save the checkbox state (checked/unchecked) and to test adding and removing a class.
Saving the checked state and the add/remove the style sheets from the code above this is what I want to achieve.
document.addEventListener('DOMContentLoaded', function () {
chrome.storage.local.get('enabled', function (result) {
if (result.enabled != null) {
a.checked = result.enabled;
}
});
chrome.storage.local.set({
'enabled': a.getAttribute('aria-checked') === 'true'
}, function () {
});
});
CodePudding user response:
I find this in chrome storage documentation. You must declare the "storage" permission in the extension manifest to use the storage API. For example:
{
"name": "My extension",
...
"permissions": [
"storage"
],
...
}
CodePudding user response:
chrome.storage.local.set({key: value}, function() {
console.log('Value is set to ' value);
});
chrome.storage.local.get(['key'], function(result) {
console.log('Value currently is ' result.key);
});
as you see in the code when you use a string key you don't use "" and if use a variable you put it in [] like this ['key'] I hope this is the problem
document.addEventListener('DOMContentLoaded', function () {
chrome.storage.local.get(['enabled'], function (result) {
if (result.enabled != null) {
a.checked = result.enabled;
}
});
chrome.storage.local.set({
enabled: a.getAttribute('aria-checked') === 'true'
}, function () {
});
});