Skip to content
AnswerWell geo Documentation

Research · 9 min read · Answerwell

Extension Message Passing, Ports, and Native Hosts

How browser extension parts talk via runtime messaging, externally_connectable, web pages, and native applications—with limits and checks.

This page summarizes Chrome Extensions documentation on message passing: moving data between a service worker, extension pages, content scripts, other extensions, web apps, and (where supported) native applications. Different contexts cannot share JavaScript memory, so coordinated work relies on chrome.runtime / browser.runtime APIs, manifest rules such as externally_connectable, and sometimes window.postMessage on the host page.

Message passing: why extensions cannot share variables directly

Section titled “Message passing: why extensions cannot share variables directly”

Message passing answers the case where a content script needs data or actions from the service worker (or the reverse), but the two run in isolated worlds.

Much like two browser windows opened to the same web page, these two contexts cannot directly access each other’s values. Instead, the extension can use message passing to coordinate across these different contexts.

— Chrome, browser.runtime

Messaging APIs allow you to communicate between different scripts running in contexts associated with your extension. This includes communication between your service worker, chrome-extension://pages and content scripts.

— Chrome, Message passing

chrome.extension (Manifest V2) and the modern stack both describe utilities for exchanging messages between extension pages and content scripts; see Message passing and browser.extension.

One-time requests: sendMessage and onMessage

Section titled “One-time requests: sendMessage and onMessage”

For a single request and optional reply, use runtime.sendMessage() or tabs.sendMessage(). Register runtime.onMessage on the receiving side.

From a content script to the service worker:

browser.runtime.sendMessage('get-user-data', (response) => {
console.log('received user data', response);
initializeUI(response);
});

The service worker handles the message and calls sendResponse:

browser.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message === 'get-user-data') {
sendResponse(user);
}
});

The same pattern appears in browser.runtime and the service worker events tutorial, where a content script sends { greeting: 'tip' } and the worker replies from browser.storage.local.

Async replies: By default, sendResponse must run synchronously. For fetch or other async work, return literal true from the listener to keep the channel open, or return a Promise (supported from Chrome 148, rolling out gradually). Multiple onMessage listeners can interact badly with async listeners that implicitly resolve to undefined (sent as null); see the examples in Message passing.

Long-lived connections: connect, Port, and named channels

Section titled “Long-lived connections: connect, Port, and named channels”

For many messages over one session, call runtime.connect() (content script → extension) or tabs.connect() (extension → content script). Each side gets a runtime.Port and uses port.postMessage / port.onMessage.

One potential use case for a long-lived connection is an automatic form-filling extension. The content script might open a channel to the extension page for a specific login, and send a message to the extension for each input element on the page to request the form data to fill in.

— Chrome, Message passing

Handle incoming connections with runtime.onConnect (or runtime.onConnectExternal for outsiders). Details and the “knock knock” example are in Message passing.

In Chrome, the message passing APIs use JSON serialization. Notably, this is different to other browsers which implement the same APIs with the structured clone algorithm.

— Chrome, Message passing

Payloads must be JSON-serializable; undefined becomes null in responses.

Content scripts: which APIs they get and how they reach the extension

Section titled “Content scripts: which APIs they get and how they reach the extension”

Content scripts run in the page’s renderer but not in the page’s JavaScript environment. They can call a limited set of APIs directly; everything else goes through messaging.

Direct access includes dom, i18n, storage, and parts of runtime (connect, getURL, id, onConnect, onMessage, sendMessage, etc.):

Content scripts can access the following extension APIs directly: … runtime.sendMessage() … Content scripts are unable to access other APIs directly. But they can access them indirectly by exchanging messages with other parts of your extension.

— Chrome, Content scripts

To load packaged files from a content script, use runtime.getURL() and declare paths under web_accessible_resources—otherwise fetches and DOM references fail. CSS can use chrome-extension://__MSG_@@extension_id__/… as shown in Content scripts.

Web page ↔ content script: window.postMessage

Section titled “Web page ↔ content script: window.postMessage”

The page and content script share the DOM but not JS globals. A site talking to your extension should post messages the content script validates, then forward via runtime.sendMessage or runtime.connect.

If the page wishes to communicate with the content script, or with the extension through the content script, it must do so through the shared DOM. An example can be accomplished using window.postMessage()

— Chrome, Content scripts

Typical pattern: the page uses window.postMessage({ type: 'FROM_PAGE', … }, '*'); the content script checks event.source === window and known event.data shapes before forwarding. Injected page scripts (no content script) cannot use runtime.sendMessage to reach DevTools UI—use a content script intermediary as in Extend DevTools.

Cross-extension messaging: extension ID and external listeners

Section titled “Cross-extension messaging: extension ID and external listeners”

Extensions can expose a API to other extensions by ID.

Listen with runtime.onMessageExternal / runtime.onConnectExternal:

Fired when a message is sent from another extension (by runtime.sendMessage). Cannot be used in a content script.

— Chrome, browser.runtime

Send to another extension by passing its ID as the first argument to runtime.sendMessage or runtime.connect. Examples with allowlisting sender.id appear in Message passing.

If you add externally_connectable and omit "ids": ["*"], you may block extensions that could previously connect:

If the externally_connectable key is not declared in your extension’s manifest, all extensions can connect, but no web pages can connect. As a consequence, when updating your manifest to use externally_connectable, if “ids”: [“*”] is not specified, then other extensions will lose the ability to connect to your extension.

— Chrome, externally_connectable

Web pages, PWAs, and IWAs: externally_connectable and who starts the conversation

Section titled “Web pages, PWAs, and IWAs: externally_connectable and who starts the conversation”

Arbitrary web-to-extension messaging is not open by default. The extension must declare allowed callers; the page must know the extension’s static ID (from chrome://extensions, install UI, or Chrome Web Store).

Arbitrary communication between Extensions and web apps is prohibited. Establishing a link requires the web app to be allowed with the Extension’s externally_connectable manifest entry and requires the app to know the Extension’s static ID. Because the Extension cannot initiate the initial contact, a “handshake” technique is necessary.

— Chrome, Connect PWAs and IWAs with Chrome Extensions

Caller Manifest pattern Notes
HTTPS PWA / site "matches": ["https://*.example.com/*"] Standard scheme; patterns cannot be overly broad (e.g. https://*/* is invalid for pages in MV2 docs; see reference for valid patterns)
Isolated Web App (IWA) "matches": ["isolated-app://…/*"] Prefer a specific Web Bundle ID over isolated-app://*/* in production
Other extensions "ids": ["…"] or "*" Optional; omitting ids denies extensions when externally_connectable is present

From the web app:

chrome.runtime.sendMessage(STATIC_EXTENSION_ID, { methodName: method });

The extension listens with runtime.onMessageExternal (e.g. proxying to chrome.runtime.restart() in the PWA/IWA guide).

It is not possible to send a message from an extension to a web page.

— Chrome, Message passing

externally_connectable does not affect content scripts—only runtime.connect / runtime.sendMessage from allowed web origins or extension IDs. Full field reference: externally_connectable.

User scripts (untrusted context) use the same send APIs but dedicated receivers on the extension side:

They’re received using dedicated event handlers (meaning, they don’t use onMessage or onConnect). These handlers are called runtime.onUserScriptMessage and runtime.onUserScriptConnect.

— Chrome, browser.userScripts

Enable with browser.userScripts.configureWorld({ messaging: true }) before sending.

Native messaging: hosts, permissions, and platform limits

Section titled “Native messaging: hosts, permissions, and platform limits”

Native messaging lets an extension talk to a registered host process over stdin/stdout JSON frames (length-prefixed). Declare "nativeMessaging" in the manifest; use runtime.connectNative() or runtime.sendNativeMessage().

These methods are not available inside content scripts, only inside your extension’s pages and service worker. To communicate from a content script to the native application, send the message to your service worker to pass it along to the native application.

— Chrome, Native messaging

The host registers a manifest with allowed_origins listing chrome-extension://EXTENSION_ID/ (no wildcards). Message size from the host is capped at 1 MB; debug output belongs on stderr, not stdout—stdout must follow the binary protocol (Native messaging).

On Googlebook OS, native messaging is not available yet; connection attempts fail and extensions should fall back to web workflows:

Native messaging isn’t available yet on Googlebook OS, but it is being worked on. … extensions that declare the nativeMessaging permission still install and run on Googlebook OS, but connection attempts fail. Make sure your extension handles connection failures gracefully

— Chrome, Adapt your extension for Googlebook OS

runtime.onConnectNative in MV2 reference is noted as supported on Chrome OS for native apps (chrome.runtime MV2).

Service worker messaging vs extension messaging

Section titled “Service worker messaging vs extension messaging”

Extension service workers support both runtime.onMessage and the generic ServiceWorkerGlobal.message, but the two channels do not interoperate:

messages sent using sendMessage() … aren’t intercepted by service worker message handlers. Likewise, messages sent using postMessage() aren’t intercepted by extension message handlers. … You should prefer extension messaging unless you have a specific reason for using service worker messaging.

— Chrome, Events in service workers

Security: limit who can talk to your extension and what leaks to the web

Section titled “Security: limit who can talk to your extension and what leaks to the web”

Stay secure ties messaging to manifest surface area:

  • externally_connectable: Restrict ids and matches to trusted partners—not open lists beyond what you need.
  • web_accessible_resources: Exposing files lets sites fingerprint installed extensions; MV3 maps each resource set to explicit matches or extension_ids (Web accessible resources, Update the manifest).
  • Native messaging: Validate sender and sanitize payloads in the service worker before calling the host (Native messaging).

When exposing assets to pages, remember declaring resources for fetch() also exposes them to any script on matching origins (Content scripts).

  • Calling sendResponse asynchronously without return true (or a returned Promise), so the sender gets an empty response.
  • Expecting runtime.sendMessage from injected page scripts without a content-script bridge (Extend DevTools).
  • Using onMessage for user-script traffic instead of onUserScriptMessage (browser.userScripts).
  • Writing debug prints to stdout in a native host, breaking the length-prefixed protocol (Native messaging).
  • Assuming the extension can message a web page directly—it cannot; only the page can initiate external messaging (Message passing).
  1. Load your unpacked extension at chrome://extensions, note the extension ID, and confirm manifest.json lists the permissions and externally_connectable / web_accessible_resources entries you expect (see externally_connectable).

  2. On a matched HTTPS page (or your IWA origin per Connect PWAs and IWAs with Chrome Extensions), open DevTools Console and call chrome.runtime.sendMessage with your extension ID; confirm the service worker’s onMessageExternal handler runs.

  3. From a tab where the content script injects, exercise internal messaging (runtime.sendMessage / connect) and verify responses using the patterns in Message passing.

  4. If you use native messaging, enable Chrome logging as described in Native messaging and retry after fixing manifest path, registry (Windows), or protocol errors.

  5. You can check automatically in Answerwell (our tool): https://answerwell.org/workspace

If something on this page is wrong or unclear, email yimasynthetic@gmail.com with the page URL and the exact statement you are asking about, and we will fix or clarify it.