IHOR.DEVKNOWLEDGE_BASE
MENU

~/blog / Security / secure-message-passing-in-chrome-extensions.md

// guide · 4 min read

Secure Message Passing in Chrome Extensions

Build Chrome extension message handlers with sender checks, bounded runtime schemas, narrow operations, asynchronous responses, and no arbitrary privileged commands.

Quick answer

Treat an extension message as an untrusted request to a capability boundary. Validate sender context, message type, field types, sizes, and allowed operation before invoking privileged APIs. Prefer commands such as getFeatureStatus or lookupItem(id) over arbitrary fetchURL, executeCode, or callChromeAPI. Being received through runtime messaging does not make page-derived data trustworthy.

The worker should own privileged decisions and return only what the caller needs. A page inspector can read the DOM and send a bounded identifier, while the worker constructs any allowed service URL itself. The related isolation guide explains why the shared DOM is untrusted; this guide focuses on authorization and contracts at the message receiver.

Practical implementation steps

Name one operation per contract

Use a discriminated message type and reject unknown commands. Define a small success and error response instead of returning raw exceptions. Version contracts deliberately if several released contexts may coexist during updates. Do not let a caller choose method names or nested property paths in a privileged namespace.

Check the expected caller

For a content-script operation, confirm the extension ID, the presence of a tab, and the allowed sender URL or origin. Apply frame restrictions if only the main frame should invoke it. For an extension-page-only operation, require that surface instead. Externally connectable messages need a separate policy and listener; do not reuse a permissive internal handler accidentally.

Validate input and recheck capability

Check unknown data at runtime, including arrays, lengths, integers, and identifiers. Schema validation does not authorize a record; verify user or tab access after parsing. Recheck relevant permissions before the privileged operation and handle races or navigation failures. Never send authentication tokens, complete server errors, or unrelated stored records back to a page-facing caller.

Handle asynchronous replies deliberately

Chrome messaging behavior depends on the supported browser version. The callback pattern that returns literal true keeps the channel available for an asynchronous sendResponse. Keep only one responder for an operation, handle rejected work, and document caller timeouts or cancellations. Chrome uses JSON serialization for messages, so do not rely on functions, DOM nodes, or special object types crossing unchanged.

Implementation example

This worker example accepts a narrow status request from a top-frame content script on one illustrative origin. It reads a local preference without disclosing the entire storage object. The manifest needs storage permission, and the content-script feature needs its own appropriate site access.

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  let allowed = false;
  try {
    allowed = sender.id === chrome.runtime.id &&
      typeof sender.tab?.id === "number" && sender.frameId === 0 &&
      new URL(sender.url ?? "").origin === "https://app.example.com";
  } catch { /* Invalid or absent sender URL remains disallowed. */ }
  if (!allowed || !message || typeof message !== "object" ||
      message.type !== "getFeatureStatus" || Object.keys(message).length !== 1) {
    return false;
  }
  chrome.storage.local.get("featureEnabled").then(
    result => sendResponse({ ok: true, enabled: result.featureEnabled === true }),
    () => sendResponse({ ok: false, code: "UNAVAILABLE" }),
  );
  return true;
});

A runtime validator and sender allowlist form separate checks. For data-dependent operations, add ownership and permission checks inside the asynchronous path. The example's origin is a placeholder, not a recommendation to allow that host. Returning false for unsupported messages lets other listeners handle their own contracts.

Tradeoffs and alternatives

One-time messages fit small request-response operations. Ports fit continuing conversations, but require disconnection handling, bounded streams, and cleanup. A port does not establish that all later payloads are trusted. Keep the same operation and validation policy regardless of transport, and avoid retaining a port merely to keep the worker alive.

Common mistakes

  • Accepting arbitrary URL fetch requests.
  • Treating TypeScript interfaces as runtime validation.
  • Ignoring sender frame or URL when the operation depends on them.
  • Returning full storage or raw errors to content scripts.
  • Forgetting true for a callback-based asynchronous response.

Production checklist

  • Commands and response shapes are explicit.
  • Sender checks match each operation's surface.
  • Inputs are bounded at runtime.
  • Permissions and ownership are checked before work.
  • Async errors and channel closure are handled.
  • Responses disclose only necessary data.

FAQ

Is checking the extension ID enough?

It identifies an extension context, but not the operation's intended tab, frame, or page-derived input. Apply the narrower checks required by the feature.

Should the worker return a whole fetch response?

Usually return a parsed, validated projection instead. It reduces exposure and keeps page-facing contracts independent of service internals.

Conclusion

Make the receiver a narrow capability API. Check who asks, validate what they ask, authorize the operation, and return a limited result. That sequence remains necessary even when every sender belongs to the same installed extension.

Primary sources

Ihor Kharchyshyn

Independent full-stack product engineer writing source-backed implementation guides for browser extensions and modern web products.

Need this implemented in a real product?

Browser tools with a clear purpose, focused permissions, and a maintainable Manifest V3 architecture.