我读了this并在其他地方搜索过,但我无法解决这个问题。我正在使用长期连接。我从内容脚本发送消息到后台,然后我想从后台发送消息到内容脚本。但是,由于某种原因,我无法在内容文件上收到消息...
内容脚本:
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"});
});
});
背景:
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"});
});
}
});
编辑:我的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"
]
}
答案 0 :(得分:0)
解决方案:我使用了#34; port&#34;的旧引用何时发生连接监听器的第二个参数(那里不可见)实际上是端口。