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

时间:2014-06-07 02:38:22

标签: 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的一部分

2 个答案:

答案 0 :(得分:2)

你快到了。要检索它,您需要实现get()的回调部分,因为Chrome通过该函数的参数将数据返回给您。所以在你的情况下你需要像

这样的东西
chrome.storage.local.get("myValue", function(obj) {
    alert(JSON.stringify(obj));
}):

由于JavaScript代码的事件驱动和单线程特性,大多数chrome API(以及大多数JavaScript代码)使用此异步构造来“返回”值,并且不同于更传统的“函数返回值的方法”。

使用这种方法调用API函数时,你还传递另一个函数(回调函数),该函数包含你在API函数完成其处理时要执行的代码(在我上面的代码中是具有警报的函数) ))。完成后的API函数然后调用回调函数及其操作结果。

答案 1 :(得分:2)

添加到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编写自己的同步缓存,可以简化整个过程。但它也并不总是合适。