我创建了一个简单的chrome扩展,为我的webPage(站点)添加了一些功能,只能通过扩展访问。是否可以直接从网页(不是通过content-script
)将postMessages发布到扩展程序的后台脚本。如果不是,chrome.runtime.connect(EXTENSION_ID);
的用例是什么,我的意思是为什么它可以从网页访问?
代码bellow表示我在页面和扩展之间的通信方式。它不起作用,onConnect.addListener
不会在myExtension中触发,port.onMessage
不会在myExtension中触发,也不会在我的webPage中触发。
https://localhost:8000/myPage.html:
var port = chrome.runtime.connect("ppibnonicgkeojloifobdloaiajedhgg"); // this is extensionId I got from chrome://extension
port.onMessage.addListener(function (event) {
console.log(event);
});
port.postMessage({type: 'PYCHAT_SCREEN_SHARE_PING', text: 'start'});
我的扩展程序中的background.js:
chrome.runtime.onConnect.addListener(function(port) {
console.log("Connected from new port ", port);
port.onMessage.addListener(function(msg) {
console.log("Got new message ", msg);
port.postMessage({type: "PYCHAT_SCREEN_SHARE_PING_RESPONSE", data: "successs"});
});
});
manifest.json的:
{
"name": "test",
"description": "test",
"version": "1.0.0",
"manifest_version": 2,
"background": {
"scripts": ["background.js"]
},
"permissions": [
"desktopCapture",
"tabs"
],
}
感谢@wOxxOm @rsanchez我应该:
chrome.runtime.onMessageExternal
externally_connectable
添加到manifest.jsonvar port = chrome.runtime.connect("ppibnonicgkeojloifobdloaiajedhgg");
port.onMessage.addListener(function (event) {
console.log(event);
});
port.postMessage({type: 'PYCHAT_SCREEN_SHARE_PING', text: 'start'});
的manifest.json
{
"name": "test",
"description": "test",
"version": "1.0.0",
"manifest_version": 2,
"background": {
"scripts": ["background.js"]
},
"permissions": [
"desktopCapture",
"tabs"
],
"externally_connectable": {
"matches": ["https://localhost:8000"]
}
}
background.js:
chrome.runtime.onConnectExternal.addListener(function(port) {
port.onMessage.addListener(function(msg) {
console.log("it works")
port.postMessage({type: "PYCHAT_SCREEN_SHARE_PING_RESPONSE", data: "successs"});
});
});