1

我正在構建Chrome擴展,並在彈出窗口中遇到以下錯誤。 enter image description here如何解決未定義和南?

我明確定義了'total'變量,並在其中存儲了一個本地存儲的值。但爲什麼我的 得到這樣的錯誤?

我想要做的事:

1)我存儲本地存儲和訪問popup.js總它變。在popup.html 2)然後,修改<p>元件

這裏是popup.html和popup.js:

popup.js:

var total,percentage; 

chrome.storage.local.get('myVariable', function (items) { 
total = (items.myVariable); 
}); 



percentage = total/7.25; 

document.getElementById("total").innerHTML = total; 
document.getElementById("percentage").innerHTML = percentage; 

popup.html:

<!DOCTYPE HTML> 

<html> 
    <head> 
    <title>Popup page</title> 
    </head> 
    <body> 

    <form name="F1" method="POST"> 
     TOTAL : <p id="total"></p> 
    PERCENTAGE : <p id="percentage"></p>  
    </form> 

    <script src="popup.js"> 

    </script> 

    </body> 
</html> 

片段從我contentscript.js

chrome.storage.local.set({ 
     'myVariable': total; 
     }); 
chrome.runtime.sendMessage({ 
    greeting: "myAction" 
}); 

在background.js我有這樣的:

chrome.runtime.onMessage.addListener(
    function (request, sender, sendResponse) { 
    if (request.greeting == "myAction") { 
     collectData(); 
    } 
}); 

我們應該添加一個偵聽器訪問本地存儲之前popup.js。我添加並檢查,但 我收到相同的結果。 這段代碼有什麼問題? 如何才能完成我要做的事情?

地方我擴展的存儲:

enter image description here

回答

2

chrome.storage.local.get回調是異步執行的,所以在您嘗試使用它之前總不會定義。如果將腳本的其餘部分移到回調中,它應該可以工作。

var total,percentage; 

chrome.storage.local.get('myVariable', function (items) { 
    total = (items.myVariable); 

    percentage = total/7.25; 

    document.getElementById("total").innerHTML = total; 
    document.getElementById("percentage").innerHTML = percentage; 
}); 
+0

我試着按建議,但它沒有工作夥計。 console.logs.items()顯示'未定義'的存儲變量。我添加了本地存儲的屏幕截圖,其中var不存儲。如何解決這個問題? – Nikhil

1

兩個主要錯誤: 1)只是在做無功x是一個無操作在JavaScript中,你必須爲它分配一個值。 2)即使你修復了你有更大的錯誤。存儲是異步的,因此在得到結果之前執行「get」之後的行。

+0

我該如何解決這個問題呢? – Nikhil

+0

放置斷點並進行調試。上面的答案我說同樣,並有一個工作示例 –

相關問題