我可以将消息从页面直接发布到扩展后台脚本,而不是chrome中的内容脚本吗?

问题描述 投票:0回答:1

我创建了一个简单的chrome扩展,为我的webPage(站点)添加了一些功能,只能通过扩展访问。是否可以直接从网页(不是通过content-script)将postMessages发布到扩展程序的后台脚本。如果不是,chrome.runtime.connect(EXTENSION_ID);的用例是什么,我的意思是为什么它可以从网页访问?

代码bellow表示我在页面和扩展之间的通信方式。它不起作用,onConnect.addListener不会在myExtension中触发,port.onMessage不会在myExtension中触发,也不会在我的webPage中触发。

enter image description here

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"
  ],
}
google-chrome-extension
1个回答
0
投票

感谢@wOxxOm @rsanchez我应该:

  • 在background.js中使用chrome.runtime.onMessageExternal
  • externally_connectable添加到manifest.json

https://localhost:8000

var 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"});
  });
});
© www.soinside.com 2019 - 2024. All rights reserved.