首先尝试在这里扩展一个chrome。我想在我的银行网站的交易列表中添加一些持久性复选框,以协助与外部预算工具协调。我已经有所有工作,但我无法从Chrome存储API(使用本地)检索数据。结果始终未定义,即使我正在测试在成功写入存储的同一回调中检索值。chrome.storage.local总是返回undefined
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
一切似乎确定。我通常使用[存储区域资源管理器](https://chrome.google.com/webstore/detail/storage-area-explorer/ocfjjjjhkpapocigimmppepjgfdecjkb)查看“本地”或“同步”状态。您也可以在控制台上记录'items'变量或'Object.keys(items)' – Ionut
Bah,Storage Area Explorer告诉我它正在存储{“rel_hash”:true},而不是将key的值用于rel_hash。 – shadfc