Chrome 本机消息传递:页面无法与扩展程序通信

问题描述

我正在编写一个简单的 Chrome 扩展程序,它使用本机消息传递与本机主机进行通信。 我已经密切关注 native messaging(扩展 本机主机)和 host-page communication 的 Chrome 文档,但我不得不说他们留下了许多重要的细节。

我可以毫无问题地启动本机主机,并且扩展程序和主机之间的通信可以正常工作。 但是,所有“前端”(页面内容脚本和后台脚本)都不能相互通信。

层级如下:

页面

window.postMessage({ type: "TO_THE_EXTENSION",text: "Hello from the webpage!" },"*");
// this never reaches the content script

contentscript.js(脚本似乎在页面上正确加载)

var port = chrome.runtime.connect(); // this throws an error

window.addEventListener("message",(event) => {
  // We only accept messages from ourselves
  if (event.source != window)
    return;

  if (event.data.type && (event.data.type === "TO_THE_EXTENSION")) {
    console.log("Content script received: " + event.data.text);
    port.postMessage(event.data.text);
  }
},false);

内容脚本的第一行立即抛出

Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.

background.js(这在从扩展工具栏重新加载扩展时有效)

var port = chrome.runtime.connectNative('my.example.app.com');

port.onMessage.addListener(function(msg) {
  console.log("Received" + msg);
});
port.ondisconnect.addListener(function() {
  console.log("disconnected");
});
port.postMessage( {'text': 'Hello'} );

manifest.json

{
  "name": "Simple extension","description": "Simple extension using native messaging","version": "1.0","manifest_version": 3,"content_scripts": [
   {
      "matches": ["http://*/*","https://*/*"],"js": ["contentscript.js"]      
   }
  ],"background": {
      "service_worker": "background.js"
  },"permissions": ["nativeMessaging"]
}

感谢任何帮助,并提供指向文档的指针,这些文档解释了整个 page -> content script -> background script -> native host应该如何实际工作。我不敢相信 Chrome 文档中没有使用本机消息传递的扩展程序的最小、完整且可验证的示例。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)