0

我已經爲我的分機下面的代碼: popup.jsChrome擴展asynchronus問題

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中)爲我的擴展,我似乎無法把localProgress在localStorage。並且我得到了一個錯誤在popup.js評論是。 我不明白爲什麼我得到的錯誤,因爲該元素的ID設置爲暫停。 有人可以幫我解決這個問題嗎?

謝謝!

-Danny-

編輯 我把它換成chrome.storage.local.setlocalStorage['isPaused']="0";但我仍然不能得到它保存在localStorage的。 我不知道如何解決異步問題..有人可以提出一些建議嗎?請問setTimeout({},1000)是否有效?(我有一個異步問題,在popup.js末尾獲得<a>元素ID)

回答

2

您有幾個錯誤。其中: 1)localStorage!= chrome.storage。閱讀文檔。 2)chrome.storage是異步的,當你設置的時候你沒有編碼。 這兩個錯誤都很嚴重。修復它們並重試。

+0

我編輯了這篇文章一點點......你能檢查一下嗎? – csanonymus

+1

您現在正在問一個不同的問題。這不是如何s.o.作品。 –

+0

接受Zig對您原始問題的回答,然後再問一個新問題。 – sowbug