如何调用chrome.storage.sync.get并在页面加载时分配变量? [英] How do I call chrome.storage.sync.get and assign variables on page load?
问题描述
我的页面只有在设置为true时才应加载特定部分.这些设置可以在存储中找到.
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 page.
I have tried the following:
var permission = true;
chrome.storage.sync.get({
history: true
}, function(items) {
permission = items.history;
});
但是在页面加载时权限将始终等于true.如果我调用另一个函数来打印权限值,那么直到之后才会调用它.
but permission will always equal true when the page loads. If I put a call to another function to print the value of permission, this will not be called until after.
我调用此函数,以及使用加载页面各部分的函数
I call this function as well as the functions loading the parts of the page using
document.addEventListener('DOMContentLoaded', function () {
我认为问题在于该函数未及时调用,但我不知道如何解决.
I think the problem is that the function is not called in time, but I don't know how to resolve this.
推荐答案
您的怀疑是正确的.从存储中检索数据后的回调可能会在页面已加载后执行.
Your suspicion is correct. The callback after data is retrieved from storage will probably execute after page is loaded already.
要解决此问题,我建议使用 Promise :
To solve this, I suggest using Promise:
var p = new Promise(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);
});
用 async/await
重写,但是我们仍然必须保证回调:
Rewritten with async/await
, but we still have to promisify the callback:
async function getFromStorage(key) {
return new Promise((resolve, reject) => {
chrome.storage.sync.get(key, resolve);
})
.then(result => {
if (key == null) return result;
else return result[key];
});
}
let permission = await getFromStorage("history");
这篇关于如何调用chrome.storage.sync.get并在页面加载时分配变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!