在没有监听器的情况下从 background.js 向 popup.js 发送消息
Sending message from background.js to popup.js without listener
我在 background.js
中有一个很长的任务 运行,我想在完成后向 popup.js
发送消息。但是,如果发送消息时页面动作还没有被点击,那么popup.js
中的监听器还没有注册,就不会收到消息。
我可以改为从 popup.js
发送消息并请求后台任务的结果作为响应。但是,不能保证任务会在那个时间点完成。
我看到的唯一解决方案是将两者结合起来:在两个文件中设置监听器并来回发送消息,比如:"Here's the result if you can hear me!" 和 "I can hear now! Send me a result if you're finished." 但是,这个解决方案对于这样一个简单的任务来说似乎过于复杂了。
那么,难道没有什么地方可以让background.js
放置结果供popup.js
自己随意检索吗?
将其存储在persistent后台页面中的全局变量,使用它是officially discouraged出于内存效率的明显原因。
background.js:
var status;
popup.js,方法一,异步,首选:
chrome.runtime.getBackgroundPage(function(bg) {
displayStatus(bg.status);
});
popup.js,方法二,同步:
if (chrome.extension.getBackgroundPage().status) {
displayStatus(bg.status);
});
使用chrome.storage API or localStorage API(后者将所有内容字符串化,但由于是同步的,您的代码会更加简洁)。
使用正常的sendMessage通信,没有什么太复杂的:
background.js:
var taskCompleted = false;
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
if (message.request == "checkStatus") {
sendResponse({done: taskCompleted});
}
});
.................
if (taskCompleted) {
chrome.runtime.sendMessage({done: true});
}
popup.js:
chrome.runtime.sendMessage({request: "checkStatus"}, function(response) {
if (response.done) {
doSomething();
}
});
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
if (message.done) {
doSomething();
}
});
我在 background.js
中有一个很长的任务 运行,我想在完成后向 popup.js
发送消息。但是,如果发送消息时页面动作还没有被点击,那么popup.js
中的监听器还没有注册,就不会收到消息。
我可以改为从 popup.js
发送消息并请求后台任务的结果作为响应。但是,不能保证任务会在那个时间点完成。
我看到的唯一解决方案是将两者结合起来:在两个文件中设置监听器并来回发送消息,比如:"Here's the result if you can hear me!" 和 "I can hear now! Send me a result if you're finished." 但是,这个解决方案对于这样一个简单的任务来说似乎过于复杂了。
那么,难道没有什么地方可以让background.js
放置结果供popup.js
自己随意检索吗?
将其存储在persistent后台页面中的全局变量,使用它是officially discouraged出于内存效率的明显原因。
background.js:
var status;
popup.js,方法一,异步,首选:
chrome.runtime.getBackgroundPage(function(bg) { displayStatus(bg.status); });
popup.js,方法二,同步:
if (chrome.extension.getBackgroundPage().status) { displayStatus(bg.status); });
使用chrome.storage API or localStorage API(后者将所有内容字符串化,但由于是同步的,您的代码会更加简洁)。
使用正常的sendMessage通信,没有什么太复杂的:
background.js:
var taskCompleted = false; chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) { if (message.request == "checkStatus") { sendResponse({done: taskCompleted}); } }); ................. if (taskCompleted) { chrome.runtime.sendMessage({done: true}); }
popup.js:
chrome.runtime.sendMessage({request: "checkStatus"}, function(response) { if (response.done) { doSomething(); } }); chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) { if (message.done) { doSomething(); } });