如何使用 Chrome.Storage 设置和获取值?

Ray*_*ayB 2 javascript google-chrome-extension

我正在尝试使用 chrome.storage.local 通过 Google Chrome 扩展进行非常简单的设置和检索

我有设置它的部分:

chrome.storage.local.set({"myValue": "All the data I need"});
Run Code Online (Sandbox Code Playgroud)

我只是不明白如何检索它。

alert(chrome.storage.local.get("myValue"));
Run Code Online (Sandbox Code Playgroud)

我读过https://developer.chrome.com/extensions/storage让我困惑的部分是为什么应该有一个函数作为 storage.local.get 的一部分

Xan*_*Xan 5

添加到 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"
Run Code Online (Sandbox Code Playgroud)

发生这种情况是因为set doesn't do anything immediately, and just adds the actual setting of the value into the execution queue for 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"
Run Code Online (Sandbox Code Playgroud)

现在,这将如何运作?

// 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){
   // ??
});
// ??
Run Code Online (Sandbox Code Playgroud)

调用外部函数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"
Run Code Online (Sandbox Code Playgroud)

因此,通常您必须使用回调来链接执行,即

// part 1
chrome.storage.local.get("A", function(data){
  //part 2
  chrome.storage.local.get("B", function(data){
    // part 3
  }
}
Run Code Online (Sandbox Code Playgroud)

有时您可以通过同时要求两者来简化上述内容:

// part 1
chrome.storage.local.get(["A", "B"], function(data){
  //part 2
  //part 3
}
Run Code Online (Sandbox Code Playgroud)

可以通过编写自己的同步缓存来简化整个事情chrome.storage;但它也不总是合适的。