How to resolve Undefined and Nan?

流过昼夜 提交于 2019-12-11 09:39:47

问题


I'm building an Chrome extension and I encountered following error in my popup.

I clearly defined 'total' variable and storing in it a value from local storage.But why am I getting such an error?

What I'm trying to do:

1)I'm storing total variable in local storage and access it from popup.js. 2)Then modify <p> elements in popup.html

Here is popup.html and 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>

Snippet from my contentscript.js

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

In background.js I've got this :

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

Should we add a listener to popup.js before accessing local storage. I added and checked but I'm getting the same result. What's wrong with this code? How can accomplish what I'm set to do?

Local storage of my extension:


回答1:


The chrome.storage.local.get callback is executed asynchronously so total doesn't get defined until after you try to use it. If instead move the rest of the script into the callback it should work.

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;
});



回答2:


Two main errors: 1) just doing var x is a no-op in javascript, you must assign it a value. 2) even if you fix that you have a bigger bug. Storage is async so the line after 'get' is executed before you have the get result.



来源:https://stackoverflow.com/questions/22501531/how-to-resolve-undefined-and-nan

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!