v145 · JavaScript · Security · demo

postMessage Origin Guard

The classic postMessage guard pattern — if (event.origin === expected) — is fragile. It breaks on opaque origins, blob: URLs, and string coercion bugs. The Chrome 145 Origin API's isSameOrigin() method replaces the string comparison with a spec-correct structural check. Send messages from different simulated origins and see how each check method handles edge cases.

Chrome 145+new Origin(url).isSameOrigin(other). In browsers without the Origin API, the demo falls back to string comparison and labels the results accordingly.

Edit the "sender origin" · choose a check method (string === vs isSameOrigin) · send a message · see which messages the receiver accepts

Before Chrome 145
if (event.origin === 'https://example.com') { /* accept */ }
↳ Breaks with trailing slash, opaque origins (null), blob: URLs, port typos…
Chrome 145+
if (new Origin(event.origin).isSameOrigin(trustedOrigin)) { /* accept */ }
↳ Spec-correct structural comparison — handles all origin edge cases.
Message sender this page
Simulated sender origin
Message
Message receiver
Allowed origin (receiver expects)
Messages will appear here…
// Origin API postMessage guard — Chrome 145
// Replace fragile string comparison with isSameOrigin()

// ❌ Old pattern — breaks with opaque origins, port typos, blob: URLs
window.addEventListener('message', (e) => {
  if (e.origin === 'https://my-app.example') {
    handleMessage(e.data);
  }
});

// ✅ Chrome 145 — spec-correct structural comparison
const trusted = new Origin('https://my-app.example');

window.addEventListener('message', (e) => {
  const sender = new Origin(e.origin);
  if (sender.isSameOrigin(trusted)) {
    handleMessage(e.data);
  }
});

// isSameOrigin edge cases handled correctly:
// - Opaque origins ('null') never equal non-opaque origins
// - blob: and data: URLs get their embedded origin compared
// - Port normalisation (e.g. https on :443 = no port)

see also