Skip to content Skip to sidebar Skip to footer

How Do I Call Chrome.storage.sync.get And Assign Variables On Page Load?

I have a page that should only load a certain portion if a setting is true. These settings are found in storage. However I am unable to retrieve these settings when loading the pag

Solution 1:

Your suspicion is correct. The callback after data is retrieved from storage will probably execute after page is loaded already.

To solve this, I suggest using Promise:

var p = newPromise(function (resolve, reject) {
    var permission = true;
    chrome.storage.sync.get({
        history: true
    }, function (items) {
        permission = items.history;
        resolve(permission);
    });
});
p.then(function (permission) {
    loadStuff(permission);
});

Rewritten with async/await, but we still have to promisify the callback:

asyncfunctiongetFromStorage(key) {
    returnnewPromise((resolve, reject) => {
        chrome.storage.sync.get(key, resolve);
    })
        .then(result => {
            if (key == null) return result;
            elsereturn result[key];
        });
}

let permission = awaitgetFromStorage("history");

Post a Comment for "How Do I Call Chrome.storage.sync.get And Assign Variables On Page Load?"