簡體   English   中英

如何使用Chrome.Storage設置和獲取值?

[英]How do you set and get values with Chrome.Storage?

我正在嘗試做一個非常簡單的設置,並使用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的一部分

你快到了。 要檢索它,您需要實現get()的回調部分,因為Chrome會通過該函數的參數將數據返回給您。 因此,在您的情況下,您將需要以下內容:

chrome.storage.local.get("myValue", function(obj) {
    alert(JSON.stringify(obj));
}):

由於JavaScript代碼具有事件驅動和單線程性質,因此大多數chrome API(以及大多數JavaScript代碼)都使用此異步構造來“返回”值,這與更傳統的“函數返回值方法”不同。

使用這種方法,當您調用API函數時,還會將另一個函數(回調函數)傳遞給它,該函數包含要在API函數完成其處理后執行的代碼(在我上面的代碼中是帶有alert()的函數)。 然后,API函數在完成時會調用回調函數及其操作結果。

要添加到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編寫自己的同步緩存,可以簡化整個chrome.storage 但這也不總是很合適。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM