![](/img/trans.png)
[英]Chrome extension long-lived message connection - how to use callback functions?
[英]Chrome extension long lived connection: retrieve message from background to content
我讀了此書並在其他地方搜索過,但無法解決此問題。 我正在使用長期連接。 我將消息從內容腳本發送到后台,然后再將消息從背景腳本發送到內容腳本。 但是,由於某些原因,我無法在內容文件上接收消息...
內容腳本:
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"
]
}
解決方案:我使用的是連接發生時的“端口”的舊引用。 偵聽器的第二個參數(在那里不可見)實際上是端口。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.