[英]Chrome extension long lived connection: retrieve message from background to content
I read this and searched on other places but I can't solve this issue. 我读了此书并在其他地方搜索过,但无法解决此问题。 I am using long-lived connections.
我正在使用长期连接。 I send a message from content script to background and after that I want to send a message from background to content script.
我将消息从内容脚本发送到后台,然后再将消息从背景脚本发送到内容脚本。 However, I am not able to receive messages on the content file for some reason...
但是,由于某些原因,我无法在内容文件上接收消息...
Content script: 内容脚本:
var port = chrome.runtime.connect({name: "my-channel"});
// receive messages
port.onMessage.addListener(function(msg) {
console.log(msg); // doesn't log anything
});
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('alertButton').addEventListener('click', function() {
// send message
port.postMessage({myProperty: "value"});
});
});
Background: 背景:
chrome.runtime.onConnect.addListener(function(port) {
if(port.name == "my-channel"){
port.onMessage.addListener(function(msg) {
// do something
// then send message to the content
port.postMessage({myProperty: "value"});
});
}
});
EDIT: my manifest.json 编辑:我的manifest.json
{
"manifest_version": 2,
"name": "Test extension",
"version": "1.0",
"browser_action": {
"default_popup": "main_ui.html",
"default_title": "Test Extension"
},
"content_scripts": [{
"matches": ["<all_urls>"],
"js": ["logic.js"]
}],
"background": {
"scripts": ["background.js"],
"persistent": true
},
"permissions": [
"tabs",
"activeTab"
]
}
solution: I was using an old reference of "port" of when connection happened. 解决方案:我使用的是连接发生时的“端口”的旧引用。 The 2nd argument of the listener (that isn't visible there) is actually the port.
侦听器的第二个参数(在那里不可见)实际上是端口。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.