我的扩展程序有以下代码: 的 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();
我正在尝试做的是我的扩展程序的某种暂停状态(如adblock),我似乎无法将isPaused放在localStorage中。我在popup.js中收到错误,其中的注释是。 我无法理解为什么我得到错误,因为该元素的id设置为暂停。 有人可以帮我解决这个问题吗?
谢谢!
-Danny -
修改
我已将chrome.storage.local.set
替换为localStorage['isPaused']="0";
但我仍然无法将其保存在localStorage中。
我不知道如何解决异步问题。有人可以建议吗? setTimeout({},1000)是否有效?(我在popup.js的末尾获取<a>
元素id时出现异步问题)
答案 0 :(得分:2)
您有几个错误。其中: 1)localStorage!= chrome.storage。阅读文档。 2)chrome.storage是异步的,当你设置时你没有为此编码。 这两个错误都很严重。修复它们并重试。