我可以通过以下方式将消息从弹出窗口发送到后台:
背景.js
chrome.runtime.onMessage.addListener(
function(request) {
alert(request.data.subject);
}
);
弹出窗口.js
chrome.runtime.sendMessage({
msg: "something_completed",
data: {
subject: "Loading...",
content: "Just completed!"
}
});
警报加载正常,但我需要做相反的事情。我希望后台在加载页面时发送 api 调用并将该 api 调用的结果发送到 popup.js 以便它可以对 DOM 进行更改。当我切换上面的代码时,没有显示警报。我的manifest.json
:
{
"name": "example",
"version": "0.0.1",
"description": "Chrome Extension's message passing example",
"browser_action": {
"default_icon": "images/get_started32.png",
"default_popup": "popup.html"
},
"background": {
"scripts": ["background.js"]
},
"content_scripts":[{
"matches":["http://*/*", "https://*/*"],
"js":["popup.js"]
}],
"permissions": [
"background","webRequest","webRequestBlocking","webNavigation","tabs","notifications"
],
"manifest_version": 2
}
从技术上讲,chrome.runtime.sendMessage会向包括弹出窗口在内的所有扩展页面发送一条消息,但这不是组织通信的方式。
请注意,弹出窗口仅在显示时运行,因此如果它被隐藏,则无法接收消息。
假设弹出窗口已经可见,解决方案通常是简单地等待后台脚本使用return true
.
popup.js 发送一条消息:
chrome.runtime.sendMessage({foo: 'bar'}, response => {
// use the response here
});
后台脚本:
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
if (msg.foo === 'bar') {
doSomeProcessing(msg).then(sendResponse);
return true;
}
});
function doSomeProcessing(msg) {
return new Promise(resolve => {
// do something async
resolve({data: 123});
});
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句