繁体   English   中英

从页面发送数据到chrome扩展程序

[英]Send data from page to chrome extension

我尝试将一些数据从Web应用程序发送到chrome扩展程序(如google文档中所述 ),但出现错误: Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist. Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.

我的内容脚本:

chrome.runtime.onMessageExternal.addListener(
  function(request, sender, sendResponse) {
    if (sender.url == blocklistedWebsite)
      return;  // don't allow this web page access
    if (request.openUrlInEditor)
      openUrl(request.openUrlInEditor);
  });

这是我的清单:

{
  "name": "test-extension",
  "version": "0.0.1",
  "manifest_version": 2,
  "background": {
    "scripts": ["src/bg/background.js"],
    "persistent": false
  },
  "content_scripts": [
    {
      "matches": ["http://localhost/*"],
      "js": ["src/inject/inject.js"]
    }
  ],
  "externally_connectable": {
    "ids": ["abcdefghijklmnoabcdefhijklmnoabc"],
    "matches": ["http://localhost/*"],
    "accepts_tls_channel_id": false
  }
}

和测试页,我正在尝试发送数据:

<body>
    <button onclick="processData()">Send data to extension</button>
  </body>
  <script>
    function processData() {
      /* ... */
      // The ID of the extension we want to talk to.
      var editorExtensionId = "abcdefghijklmnoabcdefhijklmnoabc";

      // Make a simple request:
      chrome.runtime.sendMessage(
        editorExtensionId,
        { openUrlInEditor: 'https://google.com' },
        function(response) {
          if (!response.success) handleError(url);
        }
      );
    }
  </script>

问题出在the externally_connectable配置中。 它不适用于localhost 为了在localhost主机上使用它,我在主机文件中添加了以下行:

127.0.0.1 my.localhost

然后将清单更改为:

 "externally_connectable": {
    "ids": ["*"],
    "matches": [
      "http://my.localhost/*",
    ]

这会将消息传递API公开到与您指定的URL模式匹配的任何页面。 URL模式必须至少包含第二级域-即,禁止使用主机名模式,例如“ ”,“。 com”,“。 co.uk”和“ .appspot.com”。 在网页上,使用runtime.sendMessage或runtime.connect API将消息发送到特定的应用程序或扩展

参考: https : //developer.chrome.com/extensions/messaging#external-webpage

也许是因为您的http:// localhost / *

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM