我有一个使用存储空间的 chrome 扩展程序,但无法一键从存储空间中获取值。
有一个输入字段。在用户输入一个值并按下回车键后,扩展应该从存储中获取该值并将用户的输入添加到该值中。第一次输入按它不起作用,但如果用户第二次单击回车键,则会看到存储的值。
我假设问题出在函数的排序上,但我不知道具体在哪里。
按正确顺序编码:
var repo, moduleCodes, url;
// Third process
function getStoredUrl() {
chrome.storage.sync.get(function (item) {
url = item.savedUrl;
});
}
// Fourth process
function setVariables() {
repo = document.getElementById("repo").value.toLowerCase();
moduleCodes = {
admin: "EHEALTHADM"
};
}
// Second process
function openGraph() {
getStoredUrl();
setVariables();
if (moduleCodes[repo] !== undefined) {
// ERROR: field "test" doesn't have value url, but should to have
document.getElementById("test").value = url;
//window.open(url + moduleCodes[repo]);
} else {
returnError("Can't find repo " + repo, "repo");
}
}
var enter = 13;
// First process
function inputRepoListener(e) {
"use strict";
if (e.keyCode === enter) {
openGraph();
}
}
整个代码可以在gitHub repo上看到:https://github.com/iriiiina/fisheyeGraph
这是一个典型的竞争条件,由异步方法调用引起。
对 storage.sync.get
的调用是异步的,即在检索存储值时正常的程序流继续。这意味着在存储值检索完成之前,将(仍然为空的)url
变量分配给带有 id test
的元素也会发生。
解决方案:将检索到存储值后应该发生的所有事情移动到< code>storage.sync.get的回调中。例如,如果您像这样分配< code>url,它将会工作。
chrome.storage.sync.get(function (item) {
url = item.savedUrl;
document.getElementById("test").value = url;
});
因此,您需要重新构建代码以满足此条件。