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

标签 javascript google-chrome-extension

我正在尝试使用 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 的工作原理。 setget 都是异步的,因此执行过程如下所示:

// 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){
   // ??
});
// ??

调用 setget 的外部函数只是将内容添加到队列中并完成;然后将前两项添加到队列中,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/

相关文章:

javascript - 文本中断javascript中的单引号

javascript - Bootstrap 确认图标未显示

javascript - 使用 DataTable JSON 填充下拉列表

javascript - jQuery 外部文本请求图像

google-chrome - 如何在Chrome扩展程序中读取和显示文件

javascript - Gmail 存在身份验证问题。某些功能可能无法使用

node.js - 是否可以使用 node.js 开发 Google Chrome 扩展程序?

javascript - react-native 链接给出错误 no such file or directory info.plist

google-chrome - 如何让复选框 "Allow access to file URLs"显示在我的应用程序旁边?我在 list 中有文件写入权限

javascript - 外部 Ajax : All at Once, 根据需要,还是其他?