使用chrome扩展,如何使用长寿命连接(端口)将消息从后台脚本传递到内容脚本
With a chrome extension, how do I pass a message from background script to content script using a long-lived connection (port)?
这是我的背景脚本。我可以通过弹出脚本向它发送消息。换句话说,控制台在后台页面中记录"hello"。
// background.js
chrome.runtime.onConnect.addListener(function(port){
port.onMessage.addListener(function(msg) {
if (msg.greeting == "hello") {
var port = chrome.tabs.connect(0, {name: "mycontentscript"});
port.postMessage({greeting:"hello"});
console.log('hello');
}
});
});
但是,我无法将消息从后台脚本获取到我的内容脚本。这是我的内容脚本。警报未显示。
// content.js
var port = chrome.runtime.connect({name:"mycontentscript"});
port.onMessage.addListener(function(message,sender){
if (message.greeting == "hello") {
alert('hello');
}
});
我做错了什么?谢谢
您似乎忘记了建立连接,只在创建端口后的内容脚本中使用postMessage
,并在后台页面中的runtime.onConnect.addListener()
中重用该端口。
background.js
chrome.runtime.onConnect.addListener(function(port) {
port.onMessage.addListener(function(msg) {
if (msg.greeting == "hello") {
port.postMessage({ greeting: "hello" });
console.log('hello');
}
});
});
content.js
var port = chrome.runtime.connect({ name: "mycontentscript" });
port.postMessage({greeting: "hello"});
port.onMessage.addListener(function(message) {
if (message.greeting == "hello") {
alert('hello');
}
});
我不知道我的情况是否和你的完全一样,但我也写了一个Chrome扩展,后台页面在其中向客户端发送消息。
在我的内容脚本中,我执行以下操作:
chrome.runtime.sendMessage('requestData', this.updateData.bind(this));
在我的背景脚本中,我有:
chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
sendResponse({
messages : inboxMessages,
userId : user_id
});
});
然后我的内容脚本收到消息:
this.updateData = function(data) {
//...
}
希望这对你有帮助!
在后台.js:
chrome.runtime.onConnect.addListener(function(port){//here you've got the port
port.onMessage.addListener(function(msg) {
if (msg.greeting == "hello") {
//and here you're making a new, unneeded port, for which nobody is listening.
//Use the one you've got.
var port = chrome.tabs.connect(0, {name: "mycontentscript"});
port.postMessage({greeting:"hello"});
console.log('hello');
}
});
});
使用chrome.tabs.connect从后台启动连接,并将chrome.runtime.onConnect侦听器放在选项卡的content.js中,或者像您所做的那样从选项卡启动连接,然后使用在后台的onConnect侦听器中获得的端口。只需删除
var port=chrome.tabs.connect(0, {name: "mycontentscript});
行。
相关文章:
- 选项卡侦听器未被来自后台脚本的消息激活
- 将图像从后台页面传递给内容脚本javascript
- 使用javascript后台脚本获取Yotutube频道信息
- 在chrome web商店中打开时,是否有允许执行内容/后台脚本的解决方案
- 在后台运行的脚本在出现弹出窗口时会停止
- 在chrome扩展中获取从后台页面到内容脚本的配置
- 使用chrome扩展,如何使用长寿命连接(端口)将消息从后台脚本传递到内容脚本
- Chrome扩展使用后台页面+内容脚本
- Chrome扩展:在后台页面和网站页面脚本之间进行通信的最佳方法
- 为什么chrome.sockets.tcp.create()在应用程序后台脚本中不起作用
- Chrome 打包应用 - 消息从后台传递.js传递到另一个脚本页面
- 将注入的按钮从内容脚本调用到后台.js
- 后台脚本在受限范围内运行的 Chrome 应用
- 如何停止 npm 脚本在后台自动运行
- 如何通过在后台运行安装程序或脚本来安装 NPAPI 插件
- Chrome:同时使用内容和后台脚本不起作用
- 从“选项”弹出窗口中选择一个值,然后将其保存到 Chrome.storage,以便在后台脚本中用作值
- 应用程序后台脚本,访问打开的窗口的元素
- Chrome 扩展程序:无法让消息传递在后台脚本和内容脚本之间正常工作
- 如何在后台获取 chrome 扩展程序的内容脚本