我正在使用indexedDB编写chrome扩展,并希望使用sendMessage将数据从后台页面传递到弹出窗口。
如果按下按钮,则会从弹出窗口向背景发送消息,并且应将响应写入“结果”div。
日志消息都没问题,但是没有从'openRequest.onsuccess'块中发送响应。
我不确定为什么没有从openRequest.onsuccess收到响应,但是在写入之后就是控制台消息。
来自console.log的 输出;
弹出;
processMessage() - 2
背景;
processMessage() - 2
processMessage() - 1
'结果'的内容;
processMessage() - 2
popup.js
var popupInst;
var popupPage = function() {
var mThis = this;
this.msg;
this.init = function() {
document.querySelector('#btnAdd').addEventListener('click', this.add);
};
this.add = function() {
chrome.extension.sendMessage({ add: { keyName: 'key', valueName: 'value' }}, function(response) {
mThis.msg = (response.msg)
console.log(mThis.msg);
$('#results').empty().append(mThis.msg);
});
};
}
document.addEventListener('DOMContentLoaded', function(){popupInst = new popupPage(); popupInst.init();});
background.js
var bgInst;
var backgroundPage = function()
{
var mThis = this;
this.dbName = 'test-db';
this.db;
this.init = function() {
var openRequest = window.indexedDB.open(mThis.dbName,1);
openRequest.onsuccess = function(evt) {
this.db = openRequest.result;
};
openRequest.onupgradeneeded = function(evt) {
var objStore = evt.target.result.createObjectStore(this.dbName,{keyPath:"keyName"});
objStore.createIndex("keyName","keyName",{unique:true});
objStore.createIndex("valueName","valueName",{unique:false});
};
chrome.extension.onMessage.addListener(this.processMessage);
};
this.processMessage = function(msgRequest,msgSender,msgCallback) {
if(msgRequest.add) {
var openRequest = window.indexedDB.open(mThis.dbName);
openRequest.onsuccess = function(evt) {
var str1 = 'processMessage() - 1';
msgCallback({ msg: str1 }); -> this message is never received in popup.js
console.log(str1); -> but this message is written to the log
};
var str2 = 'processMessage() - 2';
msgCallback({ msg: str2 });
console.log(str2);
}
};
}
document.addEventListener('DOMContentLoaded', function(){bgInst = new backgroundPage(); bgInst.init();});