我正在尝试使用 chrome.storage.local 通过 Google Chrome 扩展进行非常简单的设置和检索
我有设置它的部分:
chrome.storage.local.set({"myValue": "All the data I need"});
我只是不明白如何检索它。
alert(chrome.storage.local.get("myValue"));
我已阅读 https://developer.chrome.com/extensions/storage让我困惑的是为什么应该有一个函数作为 storage.local.get 的一部分
最佳答案
添加到 source.rar 的正确但简洁的答案:
您的问题也始于误解 set
的工作原理。 set
和 get
都是异步的,因此执行过程如下所示:
// 1. Suppose the stored value for A is "a"
chrome.storage.local.set({A:"b"});
// 2. The stored value for A is still "a"
发生这种情况是因为 set
不会立即执行任何操作,而只是将值的实际设置添加到 JavaScript 的执行队列中。
您也可以为 set
添加回调。设置操作后它被推送到队列:
// 1. Suppose the stored value for A is "a"
chrome.storage.local.set({A:"b"}, function(){
// 3. This will execute after the outer function finishes
// and setting is done; the value for A is "b"
});
// 2. The stored value for A is still "a"
现在,这将如何运作?
// 1. Suppose the stored value for A is "a"
chrome.storage.local.set({A:"b"}, function(){
// 3. This will execute after the outer function finishes
// and setting is done; the value for A is "b"
});
// 2. The stored value for A is still "a"
chrome.storage.local.get("A", function(data){
// ??
});
// ??
调用 set
和 get
的外部函数只是将内容添加到队列中并完成;然后将前两项添加到队列中,set
及其回调,另外两项,get
及其回调:
// 1. Suppose the stored value for A is "a"
chrome.storage.local.set({A:"b"}, function(){
// 4. This will execute after the outer function finishes
// and setting is done; the value for A is "b"
});
// 2. The stored value for A is still "a"
chrome.storage.local.get("A", function(data){
// 5. This will execute after the outer function finishes
// and everything else is done;
// the value for A is "b" and data.A is "b"
});
// 3. The stored value for A is still "a"
<小时/>
因此,通常您必须使用回调来链接执行,即
// part 1
chrome.storage.local.get("A", function(data){
//part 2
chrome.storage.local.get("B", function(data){
// part 3
}
}
有时您可以通过同时要求两者来简化上述内容:
// part 1
chrome.storage.local.get(["A", "B"], function(data){
//part 2
//part 3
}
可以通过为 chrome.storage
编写自己的同步缓存来简化整个事情;但它也并不总是合适。
关于javascript - 如何使用 Chrome.Storage 设置和获取值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24093098/