Lesson 5 of 9 · 23m
Messaging Contracts Between Contexts
Messages are your extension's internal API. Version them, validate them, choose the right channel, and design for dropped or duplicated delivery.
Once an extension grows past a demo, its contexts spend most of their time asking each other for things. The trap is treating chrome.runtime.sendMessage as a loose event bus where anyone can send anything. Treat it as an API boundary with schemas, versioning, authentication of context, and explicit failure behavior.
One-shot messages for commands and queries
// background.js
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (!isEnvelope(message)) return false;
routeMessage(message, sender)
.then(sendResponse)
.catch(error => sendResponse({ ok: false, error: error.message }));
return true;
});// content.js
const response = await chrome.runtime.sendMessage({
ns: "link-audit",
v: 1,
type: "scan-current-page",
requestId: crypto.randomUUID()
});
if (!response?.ok) throw new Error(response?.error ?? "scan failed");The envelope is the important part. A namespace prevents collisions with future features, v lets you evolve payloads, and requestId lets you correlate retries. The response should itself be a structured result, not whichever object some branch happened to return.
Validate sender and payload every time
function isEnvelope(value) {
return value && value.ns === "link-audit" && value.v === 1 && typeof value.type === "string";
}sender.tab can be absent for popup or extension-page messages. sender.url is untrusted information about a web page, not proof of intent. Never allow a message type such as eval, arbitrary script URL loading, or "run this selector and return innerHTML" unless you are intentionally building an injection API.
Choose the transport deliberately
Use one-shot messaging for commands, queries, and short tasks. Use ports for streaming progress or long-lived collaboration:
const port = chrome.runtime.connect({ name: "scan-progress" });
port.postMessage({ type: "start", url: location.href });
port.onMessage.addListener(msg => renderProgress(msg));Ports still die when either side dies. Reconnect with backoff, resume from a checkpoint, and never assume ordering across reconnects. chrome.tabs.sendMessage targets content scripts; chrome.runtime.sendMessage targets extension contexts. Mixing them up is the classic "message never arrives" bug.
External and native messaging are separate trust boundaries
externally_connectable lets selected websites message the extension, which means public input crosses into privileged code. Native messaging launches a local process and is stronger still. Both need narrower review than ordinary internal messages, because now the browser or operating system is part of your attack surface.
Field notes
- Async listeners must return
truesynchronously if they will callsendResponselater. - Message payloads are structured-cloned; functions, class instances, and most DOM nodes do not survive.
- A missing receiver often means the content script was never injected into that frame — inspect frame and target before blaming messaging.
- Duplicate delivery is possible in real usage; make state-changing messages idempotent.
Was this lesson helpful?