我的扩展程序有以下代码: 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){
});
}
背景.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 设置为暂停。 有人可以帮我解决这个问题吗?
谢谢!
-丹尼-
编辑
我已经替换了chrome.storage.local.set
与 localStorage['isPaused']="0";
但我仍然无法将其保存在 localStorage 中。
我不知道如何解决异步问题..有人可以提出建议吗? setTimeout({},1000) 会起作用吗?(我在获取 popup.js 末尾的 <a>
元素 id 时遇到异步问题)
最佳答案
您有几个错误。他们之中: 1) localStorage!= chrome.storage。阅读文档。 2) chrome.storage 是异步的,当你设置时你并没有为此编码。 这两个错误都是严重的。修复它们并重试。
关于javascript - Chrome扩展异步问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22127775/