chrome.storage 未按预期工作

chrome.storage not working as expected

我正在尝试在 chrome 存储中保存字典对象列表。但是下面的代码似乎没有按预期工作。

当第一次加载扩展且存储中没有 goal 对象时,应设置 runtime.lasterror 对象并执行该部分中的代码。但事实并非如此。

当我取消注释 chrome.storage.sync.set 行并保存对象时,下一次我调用函数期望它保存列表时,它没有。它不提供任何警告框。

function isPgUrl(pg_url,gl_name) {
  if(pg_url && gl_name) {

    dic_url={
      "name":gl_name,
      "pg_url":pg_url
    }

    //chrome.storage.sync.set({"goal":[dic_url]});

    chrome.storage.sync.get(["goal"], function(data) {
      if(chrome.runtime.lastError) {
        chrome.storage.sync.set({"goal":[dic_url]},function() {
          alert("blah");
        });
        alert("here");
        return;
      }
      var list=data.goal;
      list.append(dic_url);
      alert(list);
      chrome.storage.sync.set({"goal":list},function() {
        alert("lalala");
        return;
      });     
    });
  } 
}
  1. 您永远不会 chrome.runtime.lastError 设置缺失数据。这也不例外 - 您只会获得 undefined 值。所以你的支票应该是:

    if(!data.goal) { ... }
    

    if(typeof data.goal === "undefined") { ... }
    
  2. 如果您取消注释该行,您需要注意 chrome.storage 是异步的:数据在 .set() 的回调之前不会存储。因此,您在调用 .set() 后立即执行的 .get() 可能会获取旧存储视图的快照 - 使您的代码在 list.append(dic_url);

    处失败

    并不是说 Array.prototype.append 本来就存在。你应该使用 .push().

  3. Chrome 存储有一种更有效的方法来设置默认值,如果不在存储中,通过使用对象作为查询:

    chrome.storage.sync.get({key: "defaultValue"}, function(data) {
      // data.key will be the stored value, or "defaultValue" if not in storage
    });
    

因此,如果我正确理解了您的代码的用途(将 dic_url 附加到存储中的 goal),那么这样做就可以了:

// Makes more sense to default to empty list
chrome.storage.sync.get({goal: []}, function(data) {
  var list = data.goal;
  list.push(dic_url);
  chrome.storage.sync.set({goal: list}, function() {
    // Stoarge updated, dic_url appended to goal
  });
  // Storage is not yet updated - set() is async
});
// Storage is not yet updated - get()/set() are async