javascript - 每次加载页面时,如何从后台向 Chrome 扩展程序中的弹出窗口发送消息?
问题描述
我可以通过以下方式从弹出窗口向后台发送消息:
背景.js
chrome.runtime.onMessage.addListener(
function(request) {
alert(request.data.subject);
}
);
popup.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});
});
}
推荐阅读
- cassandra-3.0 - 无效查询异常
- reactjs - 如何在 reactjs 组件中动态加载 json?
- python - 如何使用 Python 一次播放两个声音?
- python - 使用 IF 语句的 Python 用户定义函数不起作用
- xamarin.forms - 如何将 stacklayout 内容转换为 xamarin 形式的流
- python - 没有for循环的意大利面条情节?
- optimization - Webpack 4 SplitChunkPlugin 的 maxSize 与 maxInitialRequests
- mongodb - MongoDB计算不同的项目
- git - Heroku git push - “致命:远程端意外挂断”
- docker - 如何为 docker 并行测试设置机器人框架项目