You have several errors. Among them: 1) localStorage != chrome.storage. read the docs. 2) chrome.storage is async and you are not coding for that when you set. Both errors are grave. Fix them and try again.
Chrome extension asynchronus issue
题
I have the following code for my extension : popup.js
var p,textNode,a;
chrome.runtime.sendMessage({method: "getSett"}, function(response) {
if(response === "1") {
div=document.getElementById('content');
p= document.createElement('p');
textNode=document.createTextNode('The extension is paused');
p.appendChild(textNode);
div.appendChild(p);
a = document.createElement('a');
a.href ="#";
a.setAttribute('id','pause');
a.innerHTML="unpause";
div.appendChild(a);
}
else {
div=document.getElementById('content');
p= document.createElement('p');
textNode=document.createTextNode('The extension is running');
p.appendChild(textNode);
div.appendChild(p);
a = document.createElement('a');
a.href = "#";
a.setAttribute('id','pause');
a.innerHTML = "pause";
div.appendChild(a);
}
});
var link=document.getElementById('pause');
link.onclick=function() { //Uncaught TypeError: Cannot set property 'onclick' of null
chrome.runtime.sendMessage({method: "change"}, function(response){
});
}
background.js
function changeIcon(){
if (localStorage['isPaused']=='1') {
chrome.browserAction.setIcon({path:{'19': "icons/icon_19_grayscale.png", '38': "icons/icon_19_grayscale.png"}});
}
else{
chrome.browserAction.setIcon({path:{'19': "icons/icon_19.png", '38': "icons/icon_19.png"}});
}
}
function optionsSet(){
localStorage['isPaused']="0";
}
chrome.extension.onMessage.addListener(function(message, sender, sendResponse) {
if (message.type === 'getSett') {
var result = localStorage.getItem(isPaused.value);
sendResponse(result);
}
else if(message.type === 'change') {
var result = localStorage.getItem(isPaused.value)
if(result==="1") {
changeIcon();
localStorage['isPaused']="0";
}
else {
changeIcon();
localStorage['isPaused']="1";
}
sendResponse('changed');
}
else if(message.type === 'resume') {
localStorage['isPaused']="0";
var response = "0";
changeIcon();
sendResponse(response);
}
}
optionsSet();
What I'm trying to do is some kind of pause state(like in adblock) for my extension and I can't seem to put isPaused in localStorage .And I get an error in the popup.js where the comment is. I can't understand why I get the error because the element has the id set to pause. Can someone please help me sort this out?
Thank you!
-Danny-
EDIT
I've replaced chrome.storage.local.set
with localStorage['isPaused']="0";
but I still can't get it to save it in localStorage.
I have no idea how to solve the async problem..Could someone suggest something? Would a setTimeout({},1000) work?( I have an async problem in getting the <a>
element id at the end of popup.js)
没有正确的解决方案
其他提示