Extension Message Passing, documentId Targets, and CDP Sessions
How Chrome extensions route messages with tabId, frameId, and documentId, and how CDP targets and sessions relate on the page and in remote browsers.
This page summarises Chrome extension messaging APIs and frame or document targeting, and relates them to Chrome DevTools Protocol (CDP) target and session identifiers as described in Chrome’s browser.debugger API and Cloudflare’s browser agent examples. The same ideas recur across runtime, tabs, scripting, cookies, webNavigation, and related references: which execution context you are talking to, and whether you use one-shot messages or long-lived ports.
Extension messaging: one-shot messages vs Port channels
Section titled “Extension messaging: one-shot messages vs Port channels”Extension parts—service worker, options UI, content scripts in tabs—communicate with runtime.sendMessage, tabs.sendMessage, or long-lived runtime.Port objects from runtime.connect, tabs.connect, or runtime.connectNative (native messaging needs the nativeMessaging permission per runtime permissions).
Sends a single message to event listeners within your extension or a different extension/app. Similar to runtime.connect but only sends a single message, with an optional response. … Note that extensions cannot send messages to content scripts using this method. To send messages to content scripts, use tabs.sendMessage.
— Chrome,
browser.runtimesendMessage()
Sends a single message to the content script(s) in the specified tab. The runtime.onMessage event is fired in each content script running in the specified tab for the current extension.
— Chrome,
browser.tabssendMessage()
| Mechanism | Typical sender → receiver | Targets content scripts? | Response |
|---|---|---|---|
runtime.sendMessage |
Extension frame ↔ extension / other extension | No (use tabs.sendMessage) |
Promise / callback |
tabs.sendMessage |
Service worker ↔ tab content scripts | Yes (all frames unless narrowed) | Promise (Chrome 99+) |
runtime.connect / tabs.connect |
Any allowed pair via Port |
tabs.connect reaches content scripts |
Ongoing postMessage |
Messages must be JSON-serialisable:
The message to send. This object should be JSON-ifiable.
— Chrome,
browser.runtimePort.postMessage
For a minimal service-worker → active tab pattern, see tabs messaging example:
async function sendMessageToActiveTab(message) { const [tab] = await browser.tabs.query({ active: true, lastFocusedWindow: true }); const response = await browser.tabs.sendMessage(tab.id, message);}runtime.sendRequest in Manifest V2 is deprecated in favour of runtime.sendMessage.
Options pages and missing tab on the sender
Section titled “Options pages and missing tab on the sender”If the options UI talks to the background with runtime.connect or runtime.sendMessage, the sender is not tied to a browser tab:
If an extension’s options page sends a message using runtime.connect() or runtime.sendMessage(), the sender’s tab will not be set, and the sender’s URL will be the options page URL.
— Chrome, Give users options — Messaging APIs
Plan security checks around MessageSender (below), not only tab.id.
tabId, frameId, and documentId: how to address one frame
Section titled “tabId, frameId, and documentId: how to address one frame”Many APIs accept tabId, frameId, and (Chrome 106+) documentId to pin a call to one document in a tab. The same validation pattern appears on cookies, webNavigation, and MV2 cookies:
The unique identifier for the document. If the frameId and/or tabId are provided they will be validated to match the document found by provided document ID.
— Chrome,
browser.cookiesproperties
tabId identifies the tab; frameId is 0 for the top frame and positive for nested frames (MessageSender). documentId is a UUID for a specific document instance—useful after navigation when frame indices shift but you stored the document id from an earlier event.
Injection results tie execution to document and frame (scripting, userScripts):
documentId — The document associated with the injection.
frameId — The frame associated with the injection.
Narrowing tabs.sendMessage and tabs.connect to one document or frame
Section titled “Narrowing tabs.sendMessage and tabs.connect to one document or frame”Without options, tabs.sendMessage and tabs.connect fan out to every content-script frame in the tab. To target one frame or document, pass connectInfo / options (tabs API):
documentId … Send a message to a specific document identified by documentId instead of all frames in the tab.
frameId … Send a message to a specific frame identified by frameId instead of all frames in the tab.— Chrome,
browser.tabssendMessage()parameters
The same documentId / frameId options apply to tabs.connect(). Host permission APIs such as permissions can scope by documentId or tabId when removing host access for a specific top-level document.
MessageSender: what the receiver knows about the sender
Section titled “MessageSender: what the receiver knows about the sender”MessageSender is attached to ports from onConnect listeners and describes who opened the channel (runtime API):
An object containing information about the script context that sent a message or request.
— Chrome,
MessageSender
Useful fields include documentId, frameId, origin, url, tab, and documentLifecycle (Chrome 106+). For trust decisions, origin can differ from url:
The origin of the page or frame that opened the connection. It can vary from the url property (e.g., about:blank) or can be opaque (e.g., sandboxed iframes). This is useful for identifying if the origin can be trusted if we can’t immediately tell from the URL.
— Chrome,
MessageSenderorigin
In iframes, url is the frame URL, not the parent page URL:
The URL of the page or frame that opened the connection. If the sender is in an iframe, it will be iframe’s URL not the URL of the page which hosts it.
— Chrome,
MessageSenderurl
Filter runtime.onMessage / onConnect with these fields instead of assuming a single frame per tab.
Port lifetime: disconnects, multiple frames, and common mistakes
Section titled “Port lifetime: disconnects, multiple frames, and common mistakes”Ports are the two-way channel created by tabs.connect, runtime.connect, or runtime.connectNative (message passing):
Ports are designed as a two-way communication mechanism between different parts of an extension. When part of an extension calls tabs.connect(), runtime.connect() or runtime.connectNative(), it creates a Port that can immediately send messages using postMessage().
— Chrome, Message passing — Port lifetime
Calling tabs.connect on a multi-frame tab fires runtime.onConnect once per frame with a port each; the same applies to runtime.connect across extension frames.
onDisconnect means there is no valid peer anymore—navigation, missing listeners, or disconnect() on the other end (Port lifetime):
This event fires when there are no valid ports at the other end of the channel, which can have any of the following causes: … The tab containing the port is unloaded … All frames that received the port (via runtime.onConnect) have unloaded.
— Chrome, Message passing — Port lifetime
Typical mistakes:
- Using
runtime.sendMessageto reach a content script (must usetabs.sendMessageortabs.connect). - Broadcasting to all frames when only one iframe should act (omit
documentId/frameId). - Treating one
onDisconnectas “channel dead forever” while other frame ports may still be active. - Ignoring
runtime.lastErrorin callback-style APIs (runtimelastError); promise-based calls reject instead.
Posting to a disconnected port throws (Port.postMessage).
CDP debug targets, sessionId, and remote browser control
Section titled “CDP debug targets, sessionId, and remote browser control”Separately from extension messaging, CDP names targets (tabs, iframes, workers) and sessions for sending protocol commands. Chrome exposes this to extensions via browser.debugger (and MV2 chrome.debugger).
Targets represent something which is being debugged—this could include a tab, an iframe or a worker. Each target is identified by a UUID and has an associated type (such as iframe, shared_worker, and more).
— Chrome,
browser.debuggerTargets
Attach with a required protocol version, then send methods:
Attaches debugger to the given target.
— Chrome,
browser.debuggerattach()
Sends given command to the debugging target.
— Chrome,
browser.debuggersendCommand()
Debuggee is identified by one of tabId, extensionId, or targetId. From Chrome 125+, DebuggerSession adds optional sessionId for child protocol sessions within a root attach (DebuggerSession):
If sessionId is specified when passed to sendCommand, it targets a child protocol session within the root debuggee session.
— Chrome,
browser.debuggerDebuggerSession
getTargets() returns TargetInfo (id, type, url, tabId for pages, attached, etc.).
Cloudflare’s browser agent example wraps the same ideas for Workers: cdp.attachToTarget returns a sessionId, and page-scoped commands require that session on cdp.send:
Attach to a target and get a session ID. Uses Target.attachToTarget with flatten: true.
— Cloudflare, Browser agent —
cdp.attachToTarget
Send a CDP command and wait for the response. … options.sessionId string Target session ID (required for page-scoped commands)
— Cloudflare, Browser agent —
cdp.send
Product APIs build on targets: Human in the loop uses cdp.send("Cloudflare.getHandoffState", { targetId }); Live View notes listing targets yields devtoolsFrontendUrl per page target. Client SDKs gained Targets.Close() for a specific browser target (changelog).
Common conclusion: extension documentId / frameId / tabId address which page context receives JS messages; CDP targetId / sessionId address which debug target and protocol session receives CDP methods. You often need both mental models—automation via CDP, in-page logic via content scripts and tabs.sendMessage.
Related page messaging (not extension tabs)
Section titled “Related page messaging (not extension tabs)”workbox-window messageSW() sends data to a service worker and waits for a reply via event.ports[0].postMessage in the worker—same postMessage pattern, different endpoints. Embedded webview contentWindow.postMessage follows the web postMessage origin rules. Workers WebSockets send() is unrelated to extension ports; objects must be stringified for the wire.
How to check this on your site
Section titled “How to check this on your site”-
Load your extension unpacked and confirm content scripts receive
tabs.sendMessageonly when the target tab matches your host permissions, using the pattern in tabs — Pass a message to a selected tab. -
Log
sender.documentId,sender.frameId, andsender.urlinruntime.onMessagewhile messaging from an iframe; compare with the fields documented on MessageSender. -
Repeat the same message with and without
options.documentIdoroptions.frameIdontabs.sendMessageand verify only the intended frame handles it. -
If you use the debugger permission, call
browser.debugger.getTargets()beforeattach/sendCommandand confirmTargetInfo.attachedandtypematch the tab or worker you expect. -
You can check automatically in Answerwell (our tool): https://answerwell.org/workspace
Report an error or ask a question
Section titled “Report an error or ask a question”If something on this page is wrong or unclear, email yimasynthetic@gmail.com with the page URL and the exact sentence you are asking about, and we will correct or clarify it.