chrome.storage.local始终返回undefined

时间:2017-03-27 18:57:10

标签: javascript google-chrome google-chrome-extension

首次尝试镀铬扩展程序。我想在银行网站上的交易列表中添加一些持久性复选框,以帮助协调外部预算工具。我已经完成了所有工作但我无法从chrome存储API中检索数据(使用本地)。结果总是未定义的,即使我正在测试在成功写入存储的同一回调中检索值。

的manifest.json:

{
  "name": "Reconciler",
  "version": "1.0.0",
  "manifest_version": 2,
  "background": {
    "scripts": ["injector.js"],
    "persistent": false
  },
  "permissions": [
    "activeTab",
    "storage",
    "https://mybank*"
  ],
  "browser_action": {
    "default_title": "Add reconciling buttons"
  }
}

injector.js:

chrome.browserAction.onClicked.addListener(function(tab) {
    chrome.tabs.insertCSS(null, {file: "reconciler.css"});
    chrome.tabs.executeScript(null, {file: "jquery-3.2.0.min.js"});
    chrome.tabs.executeScript(null, {file: "md5.js"});
    chrome.tabs.executeScript(null, {file: "reconciler.js"});
});

reconciler.js:

$("#transactions thead tr").append("<th class='reconcile'>Reconcile</th>");

$("#transactions tbody tr").each(function(){
    $this = $(this);
    var rel_hash = "md5_" + hex_md5($this.find("img.expand-trans").first().attr("rel"));
    $this.append("<td class='reconcile'><input type='checkbox' id='" + rel_hash + "' name='" + rel_hash + "'></td>");
    chrome.storage.local.get(rel_hash, function(items) {
        $("#"+rel_hash).attr("checked", items[rel_hash]);
    });
});

$("#transactions input[type=checkbox]").change(function(){
    var rel_hash = $(this).attr("id");
    var checked = this.checked;
    chrome.storage.local.set({rel_hash: checked}, function() {
        if(chrome.runtime.lastError) {
            console.error(
                "Error setting " + key + " to " + JSON.stringify(data) +
                ": " + chrome.runtime.lastError.message
            );
        } else {
            console.log('Saved ' + rel_hash + '=' + checked);
            chrome.storage.local.get(rel_hash, function(items) {
                console.log(rel_hash + "=" + items[rel_hash]);
            });
        }
    });
});
检查和取消选中时

控制台输出:

Saved md5_516654acf57d9bd95cdbe497f7ca6c8d=true
md5_516654acf57d9bd95cdbe497f7ca6c8d=undefined
Saved md5_516654acf57d9bd95cdbe497f7ca6c8d=false
md5_516654acf57d9bd95cdbe497f7ca6c8d=undefined
Saved md5_ee541d5b1d95768cef9c257ca88c8ced=true
md5_ee541d5b1d95768cef9c257ca88c8ced=undefined

1 个答案:

答案 0 :(得分:0)

问题不在于存储API交互;这是我试图定义要发送到存储API的对象的方式。我需要设置一个动态密钥:

....
var data = {};
data[rel_hash] = checked;
chrome.storage.local.set(data, function() {
....