First attempt at a chrome extension here. I want to add some persistent checkboxes to a transaction list on my banks website to aid reconciling with an external budgeting tool. I've got everything working but I can't retrieve the data from the chrome storage API (using local). The result is always undefined, even though I'm testing retrieving the value in the same callback where it was successfully written to storage.
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]);
});
}
});
});
console output when checking and unchecking:
Saved md5_516654acf57d9bd95cdbe497f7ca6c8d=true
md5_516654acf57d9bd95cdbe497f7ca6c8d=undefined
Saved md5_516654acf57d9bd95cdbe497f7ca6c8d=false
md5_516654acf57d9bd95cdbe497f7ca6c8d=undefined
Saved md5_ee541d5b1d95768cef9c257ca88c8ced=true
md5_ee541d5b1d95768cef9c257ca88c8ced=undefined