【发布时间】:2017-11-26 08:59:24
【问题描述】:
我有一个在多个函数中需要的字符串。因此我想将它保存在一个变量中。
但是当我尝试在函数中分配它时,它不会更新变量。
var auth_code = "na";
function safeAuthCode(authcode){
auth_code = authcode;
console.log(auth_code);
}
“auth_code”此时在控制台中打印得很好,但是当我稍后尝试使用它时,它只包含“na”。
不知道我做错了什么:/
编辑:
这是调用safeAuthCode的函数:
function auth(){
chrome.identity.launchWebAuthFlow({
"url": "https://accounts.spotify.com/authorize?client_id="+client_id+
"&redirect_uri="+ encodeURIComponent(redirectUri) +
"&response_type=code"+
"&scope=" + encodeURIComponent(scopes),
"interactive": true
},
function(redirect_url) {
var url = new URL(redirect_url);
var code = url.searchParams.get("code");
safeAuthCode(code);
});
}
【问题讨论】:
-
没有足够的代码来做出有根据的猜测,如果你做出minimal reproducible example,你可能会排除为什么会发生这种情况
-
您是否有可能在代码的多个部分中创建变量?也许保存的值将来会被覆盖。这种数据可能应该保存到
sessionStorage,但这样会更有意义。然后您可以在读取/保存时使用getItem和setItem -
不,它只设置一次。该代码是 chrome 扩展的一部分。我还能使用会话存储吗? “window.sessionStorage.setItem('authcode', auth_code);”和“console.log(window.sessionStorage.getItem('authcode'));”只返回 null :/
-
哦,从标签或问题中不清楚您的代码是扩展名。但是有
chrome.storage对象,可用于保存数据
标签: javascript variables