runtime.sendMessage()

Sends a single message to event listeners within your extension or a different extension.

If sending to your extension, omit the extensionId 自变量。 runtime.onMessage event will be fired in each page in your extension, except for the frame that called runtime.sendMessage .

If sending to a different extension, include the extensionId argument set to the other extension's ID. runtime.onMessageExternal will be fired in the other extension.

Extensions cannot send messages to content scripts using this method. To send messages to content scripts, use tabs.sendMessage .

This is an asynchronous function that returns a Promise .

注意: You can also use a connection-based approach to exchange messages .

句法

var sending = browser.runtime.sendMessage(
  extensionId,             // optional string
  message,                 // any
  options                  // optional object
)

					

参数

extensionId 可选

string . The ID of the extension to send the message to. Include this to send the message to a different extension. If the intended recipient has set an ID explicitly using the 应用程序 key in manifest.json, then extensionId should have that value. Otherwise it should have the ID that was generated for the intended recipient.

extensionId is omitted, the message will be sent to your own extension.

message

any . An object that can be structured clone serialized (see Data cloning algorithm ).

选项 可选

对象 .

includeTlsChannelId 可选

boolean . Whether the TLS channel ID will be passed into runtime.onMessageExternal for processes that are listening for the connection event.

This option is only supported in Chromium-based browsers.

Depending on the arguments it is given, this API is sometimes ambiguous. The following rules are used:

  • if one argument is given , it is the message to send, and the message will be sent internally.
  • if two arguments are given:
    • the arguments are interpreted as (message, options) , and the message is sent internally, if the second argument is any of the following:
      1. 有效 选项 object (meaning, it is an object which contains only the properties of 选项 that the browser supports)
      2. null
      3. undefined
    • otherwise, the arguments are interpreted as (extensionId, message) . The message will be sent to the extension identified by extensionId .
  • if three arguments are given , the arguments are interpreted as (extensionId, message, options) . The message will be sent to the extension identified by extensionId .

Note that before Firefox 55, the rules were different in the 2-argument case. Under the old rules, if the first argument was a string, it was treated as the extensionId , with the message as the second argument. This meant that if you called sendMessage() with arguments like ("my-message", {}) , then it would send an empty message to the extension identified by "my-message". Under the new rules, with these arguments you would send the message "my-message" internally, with an empty options object.

返回值

A Promise . If the receiver sent a response, this will be fulfilled with the response. Otherwise it will be fulfilled with no arguments. If an error occurs while connecting to the extension, the promise will be rejected with an error message.

浏览器兼容性

BCD tables only load in the browser

范例

Here's a content script that sends a message to the background script when the user clicks the content window. The message payload is {greeting: "Greeting from the content script"} , and the sender also expects to get a response, which is handled in the handleResponse 函数:

// content-script.js
function handleResponse(message) {
  console.log(`Message from the background script:  ${message.response}`);
}
function handleError(error) {
  console.log(`Error: ${error}`);
}
function notifyBackgroundPage(e) {
  var sending = browser.runtime.sendMessage({
    greeting: "Greeting from the content script"
  });
  sending.then(handleResponse, handleError);
}
window.addEventListener("click", notifyBackgroundPage);

						

The corresponding background script looks like this:

// background-script.js
function handleMessage(request, sender, sendResponse) {
  console.log("Message from the content script: " +
    request.greeting);
  sendResponse({response: "Response from background script"});
}
browser.runtime.onMessage.addListener(handleMessage);

						

注意: Instead of using sendResponse() ,返回 Promise is the recommended approach for Firefox add-ons. Examples using a Promise are available in the examples section runtime.onMessage listener.

Example extensions

注意: This API is based on Chromium's chrome.runtime API. This documentation is derived from runtime.json in the Chromium code.

Microsoft Edge compatibility data is supplied by Microsoft Corporation and is included here under the Creative Commons Attribution 3.0 United States License.

Found a problem with this page?

最后修改: , 由 MDN 贡献者

  1. 浏览器扩展名
  2. 快速入门
    1. What are extensions?
    2. Your first extension
    3. Your second extension
    4. Anatomy of an extension
    5. Example extensions
    6. What next?
  3. 概念
    1. Using the JavaScript APIs
    2. Content scripts
    3. Match patterns
    4. Working with files
    5. 国际化
    6. Content Security Policy
    7. Native messaging
    8. Differences between API implementations
    9. Chrome incompatibilities
  4. 用户界面
    1. 用户界面
    2. Toolbar button
    3. Address bar button
    4. Sidebars
    5. Context menu items
    6. Options page
    7. Extension pages
    8. Notifications
    9. Address bar suggestions
    10. Developer tools panels
  5. 如何
    1. Intercept HTTP requests
    2. Modify a web page
    3. Insert external content
    4. Share objects with page scripts
    5. Add a button to the toolbar
    6. Implement a settings page
    7. Work with the Tabs API
    8. Work with the Bookmarks API
    9. Work with the Cookies API
    10. Work with contextual identities
    11. Interact with the clipboard
    12. Build a cross-browser extension
  6. Firefox differentiators
  7. JavaScript API
    1. Browser support for JavaScript APIs
    2. alarms
    3. bookmarks
    4. browserAction
    5. browserSettings
    6. browsingData
    7. captivePortal
    8. clipboard
    9. 命令
    10. contentScripts
    11. contextualIdentities
    12. Cookie
    13. devtools
    14. dns
    15. downloads
    16. events
    17. extension
    18. extensionTypes
    19. find
    20. history
    21. i18n
    22. identity
    23. idle
    24. management
    25. menus
    26. notifications
    27. omnibox
    28. pageAction
    29. permissions
    30. pkcs11
    31. privacy
    32. proxy
    33. runtime
      1. 方法
        1. connect()
        2. connectNative()
        3. getBackgroundPage()
        4. getBrowserInfo()
        5. getManifest()
        6. getPackageDirectoryEntry()
        7. getPlatformInfo()
        8. getURL()
        9. openOptionsPage()
        10. reload()
        11. requestUpdateCheck()
        12. sendMessage()
        13. sendNativeMessage()
        14. setUninstallURL()
      2. 特性
        1. id
        2. lastError
      3. 类型
        1. MessageSender
        2. OnInstalledReason
        3. OnRestartRequiredReason
        4. PlatformArch
        5. PlatformInfo
        6. PlatformNaclArch
        7. PlatformOs
        8. Port
        9. RequestUpdateCheckStatus
      4. 事件
        1. onBrowserUpdateAvailable
        2. onConnect
        3. onConnectExternal
        4. onInstalled
        5. onMessage
        6. onMessageExternal
        7. onRestartRequired
        8. onStartup
        9. onSuspend
        10. onSuspendCanceled
        11. onUpdateAvailable
    34. search
    35. sessions
    36. sidebarAction
    37. storage
    38. tabs
    39. theme
    40. topSites
    41. 类型
    42. userScripts
    43. webNavigation
    44. webRequest
    45. windows
  8. Manifest keys
    1. 介绍
    1. 作者
    2. background
    3. browser_action
    4. browser_specific_settings
    5. chrome_settings_overrides
    6. chrome_url_overrides
    7. 命令
    8. content_scripts
    9. content_security_policy
    10. default_locale
    11. description
    12. developer
    13. devtools_page
    14. dictionaries
    15. externally_connectable
    16. homepage_url
    17. icons
    18. incognito
    19. manifest_version
    20. name
    21. offline_enabled
    22. omnibox
    23. optional_permissions
    24. options_page
    25. options_ui
    26. page_action
    27. permissions
    28. protocol_handlers
    29. short_name
    30. sidebar_action
    31. storage
    32. theme
    33. theme_experiment
    34. user_scripts
    35. version
    36. version_name
    37. web_accessible_resources
  9. Extension Workshop
    1. Develop
    2. Publish
    3. Manage
    4. Enterprise
  10. Contact us
  11. Channels
    1. Add-ons blog
    2. Add-ons forum
    3. Add-ons chat