0

I have a chrome extension that is using storage and I can't get the value from the storage with one enter click.

There is a single input field. After the user enters a value and presses enter, the extension should take the value from storage and add the user's input to this value. The first enter press it doesn't work, but if user clicks Enter for second time, then stored value is seen.

I assume that problem is in the ordering of functions, but I can't understand where exactly.

Code in correct order:

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

The whole code can be seen on gitHub repo: https://github.com/iriiiina/fisheyeGraph

4

1 回答 1

1

这是一个典型的竞争条件,由异步方法调用引起。

调用storage.sync.get是异步的,即正常程序流程在检索存储值的同时继续进行。这意味着将(仍然为空的)url变量分配给具有 id 的元素也test发生存储值检索完成之前。

解决方案:将存储值检索到应该发生的所有事情移到storage.sync.get. 例如,如果您分配url类似的内容,它将起作用。

chrome.storage.sync.get(function (item) {
    url = item.savedUrl;
    document.getElementById("test").value = url;
});

因此,您需要重组代码以满足此标准。

于 2014-09-02T18:37:19.633 回答