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

dehrg
  • 1,721
  • 14
  • 17
irina
  • 49
  • 1
  • 6
  • `getStoredUrl` terminates before the callback to `sync.get` runs. (In fact, *all* of your code runs before the callback gets a chance to run.) See [How to return the response from an Ajax call?](http://stackoverflow.com/q/14220321/710446) – apsillers Sep 02 '14 at 18:34

1 Answers1

1

This is a typical race condition, caused by asynchronous method calls.

The call to storage.sync.get is asynchronous, i.e. the normal program flow continues while the storage values are being retrieved. This means that also the assignment of the (still empty) url variable to the element with id test happens before the storage value retrieval has finished.

Solution: Move everything that should happen after the storage value has been retrieved into the callback of storage.sync.get. If, for example, you assign the url like that, it will work.

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

So you need to restructure your code in order to meet this criteria.

devnull69
  • 16,402
  • 8
  • 50
  • 61
  • I wouldn't exactly call it a "race condition", since the two functions do not actually execute in parallel. In any case, this should be closed as a duplicate of the canonical question. – Xan Sep 02 '14 at 18:39