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

时间:2019-03-06 22:18:27

标签: javascript google-chrome google-chrome-extension

我尝试将一些数据从Web应用程序发送到chrome扩展程序(如google documentation中所述),但出现错误: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>

2 个答案:

答案 0 :(得分:1)

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

127.0.0.1 my.localhost

然后将清单更改为:

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

答案 1 :(得分:0)

  

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

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

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