chrome extension 普通网页与插件直接通信

与跨扩展消息传递类似,您的扩展可以接收和响应来自常规网页的消息。要使用此功能,您必须首先在 manifest.json 中指定要与哪些网站进行通信。例如:

"externally_connectable": {
  "matches": ["https://*.example.com/*"]
}

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

// The ID of the extension we want to talk to.
var editorExtensionId = "abcdefghijklmnoabcdefhijklmnoabc";

// Make a simple request:
chrome.runtime.sendMessage(editorExtensionId, {openUrlInEditor: url},
  function(response) {
    if (!response.success)
      handleError(url);
  });

在您的扩展中,您可以通过runtime.onMessageExternal或runtime.onConnectExternal API收听来自网页的消息,类似于跨扩展消息传递。只有网页可以发起连接。这是一个例子:

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);
  });

#externally_connectable 也是扩展与扩展之间通信的配置key

"externally_connectable": {
    // Extension and app IDs. If this field is not specified, no
    // extensions or apps can connect.
    "ids": [
      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
      "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
      ...
      // Alternatively, to match all extensions and apps, specify only
      // "*".
      "*"
    ],
    // Match patterns for web pages. Does not affect content scripts.
    // If this field is not specified, no webpages can connect.
    "matches": [
      "https://*.google.com/*",
      "*://*.chromium.org/*",
      ...
    ],
    // Indicates that the extension would like to make use of the TLS
    // channel ID of the web page connecting to it. The web page must
    // also opt to send the TLS channel ID to the extension via setting
    // includeTlsChannelId to true in runtime.connect's connectInfo
    // or runtime.sendMessage's options.
    "accepts_tls_channel_id": false
  }

externally_connectable 清单键可以具有以下属性:

  • ids(字符串数组) - 可选

    1. 允许连接的扩展程序或应用程序的 ID。如果留空或未指定,则无法连接任何扩展程序或应用程序

    2. 通配符"*"将允许所有扩展程序和应用程序连接

  • matches(字符串数组) - 可选

    1. 允许连接的网页的 URL 模式。这不会影响内容脚本。如果留空或未指定,则无法连接任何网页。

    2.  模式不能包括通配符域或(有效)顶级域的子域;*://google.com/*andhttp://*.chromium.org/*是有效的,而, http://*/*, *://*.com/*, 甚至http://*.appspot.com/*不是。

  • accepts_tls_channel_id(布尔) - 可选

    1. 如果为true,消息通过runtime.connect或runtime.sendMessagetrue发送的消息将设置runtime.MessageSender.tlsChannelId

    2. 如果为false,则在任何情况下都不会设置runtime.MessageSender.tlsChannelId

注意点

  1. 同步接收信息时,使用async/await+promise的方式
  2. 当检测到匹配的URL时,浏览器会自动地将chrome.runtime注入到该page页面的全局变量中,所以可以通过chrome.runtime?的方式来检测是否安装了该插件,当然这不足以确定是否是自己的插件,最好还是与插件通信返回后,获取到确认信息,才能确定自己的插件是处于激活状态

你可能感兴趣的:(extension,chrome,前端,javascript)