与跨扩展消息传递类似,您的扩展可以接收和响应来自常规网页的消息。要使用此功能,您必须首先在 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": {
- // 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(字符串数组) - 可选
允许连接的扩展程序或应用程序的 ID。如果留空或未指定,则无法连接任何扩展程序或应用程序
通配符"*"将允许所有扩展程序和应用程序连接
matches(字符串数组) - 可选
允许连接的网页的 URL 模式。这不会影响内容脚本。如果留空或未指定,则无法连接任何网页。
模式不能包括通配符域或(有效)顶级域的子域;*://google.com/*andhttp://*.chromium.org/*是有效的,而
accepts_tls_channel_id(布尔) - 可选
如果为true,消息通过runtime.connect或runtime.sendMessagetrue发送的消息将设置runtime.MessageSender.tlsChannelId
如果为false,则在任何情况下都不会设置runtime.MessageSender.tlsChannelId