此问题与I asked yesterday类似的javascript范围问题有关。希望您能帮助我解决此问题。

我正在使用Chrome扩展程序。 options.html将新用户电子邮件作为“用户”保存到localStorage,并在refreshUser()中调用background.html函数:

//save entered gmail address
document.getElementById("save").addEventListener(
    "click", function ()
    {
        var user = document.getElementById("getEmail").value;
        localStorage.setItem("user", user);
        chrome.extension.getBackgroundPage().refreshUser();
    } , false)


然后,我将电子邮件另存为background.html中的“ newUser”。问题是newUserrefreshUser()内部更新,但在null外部是refreshUser()

newUser = localStorage.getItem("user");
console.log("first newUser " + newUser);
//newUser=null

function refreshUser ()
{
    newUser = localStorage.getItem("user");
    console.log("newUser inside of refreshUser function " + newUser);
    //newUser is updated with saved email in localStorage
}

console.log("newUser after refreshUser() " + newUser);
//newUser=null


为什么在没有newUser关键字的情况下定义refreshUser()对于var是本地的?谢谢你的帮助!

更新资料

作为对pimvdb's answer的响应,我复制了background.html的代码。如果要按指示在newUser中使用formData,我需要在refreshUser()内部调用哪个函数?谢谢。

<html>
<script>

newUser = localStorage.getItem("user");
console.log("first newUser " + newUser);

function refreshUser ()
{
    newUser = localStorage.getItem("user");
    console.log("newUser inside of refreshUser function " + newUser);
}

console.log("newUser after refreshUser() " + newUser);

//I want to user newUser below in formData
chrome.browserAction.onClicked.addListener(function(tab)
{
    chrome.tabs.getSelected(null,
    function(tab)
    {
        // Send a request to the content script.
        chrome.tabs.sendRequest(tab.id, {action: "getDOM"},
        function(response)
        {
            var firstParagraph = response.dom;

            var formData = new FormData();
            formData.append("url", tab.url);
            formData.append("title", tab.title);
            formData.append("pitch", firstParagraph);
            formData.append("extension_user", "[email protected]");
            //I want to user newUser here:
            //formData.append("extension_user", newUser);
            console.log("newUser inside formData: " + newUser)

            var xhr = new XMLHttpRequest();
            xhr.open("POST", "http://ting-1.appspot.com/submithandlertest", true);
            xhr.onreadystatechange =
            function (aEvt)
            {
                if (xhr.readyState == 4)
                {
                    if (xhr.status == 200)
                    {
                        console.log("request 200-OK");
                        chrome.browserAction.setBadgeText ( { text: "done" } );
                        setTimeout(function ()
                        {
                            chrome.browserAction.setBadgeText( { text: "" } );
                        }, 2000);
                    }
                    else
                    {
                        console.log("connection error");
                        chrome.browserAction.setBadgeText ( { text: "ERR" } );
                    }
                }
            };
            xhr.send(formData);
        }); //chrome.tabs.sendRequest
    });
});


</script>
</html>


更新以回答pimvdb's comment

我遇到的问题是打开浏览器时加载了background.html,但是此后电子邮件已保存在options.html中。因此,refreshUser()告诉background.html从localStorage获取newUser。然后,我需要像这样在formData中使用“ newUser”:

formData.append("extension_user", newUser);


但是我现在在refreshUser()之外的“ newUser”方法是空的。我想念什么?

更新以澄清为什么某些日志未显示在控制台中

这是我的工作:

1. I reload the extension and start with localStorage empty
2. I use the extension to save a bookmark
3. all 3 logs are null as expected

 first newUser null
 newUser after refreshUser() null
 newUser inside formData: null
 request 200-ok

4. now I save user email in options as [email protected]
5. now I use the extension again to save a bookmark
6. now refreshUser is executed and the log inside the function says [email protected] and formData log says [email protected]

newUser inside of refreshUser function [email protected]
newUser inside formData: [email protected]
request 200-OK

7. but what confuses me is that now the first 2 logs do not show in the console. Why?

最佳答案

它是全局的,但是您在错误的时间访问它。

function refreshUser () { ... }只是一个函数声明;什么都没有真正执行。该声明之外的两个日志都将立即运行,此时尚未设置localStorage项(即null)。

您的措辞“ refreshUser()之后的newUser”相当含糊。它确实在声明后执行,但是newUser根本没有被更改,因此两个日志都在函数日志null之外。在尚未设置您期望的时间时,您无法访问它。

由于全局变量已更新,因此以下内容应该可以很好地记录下来。只需在refreshUser中设置它即可调用它。

function otherFunction() {
    // logs the global variable 'newUser', which is thus indeed global
    console.log("newUser inside otherFunction: " + newUser);
}

function refreshUser ()
{
    newUser = localStorage.getItem("user");
    otherFunction();
}

10-04 15:27