postMessage Validates The Sender Origin

Gate window messages by event.origin before touching data: unmatched senders are dropped and payload shape is verified independently.

JavascriptSecurity Boundaries

Code

javascriptsnippet
18 lines
if (typeof window === 'undefined') {
  console.log('DOM unavailable in this runtime');
} else {
  const trusted = 'https://app.example.com';

  // 第一道闸:来源不匹配直接丢弃,不读取任何字段
  window.addEventListener('message', (event) => {
    if (event.origin !== trusted) return;
    if (event.data?.type !== 'selection') return;

    document.title = 'picked ' + event.data.id;
  });

  // 恶意页面可以伪造任意 message:来源之外还要独立校验 payload 形状
  const forged = { type: 'selection', id: 7 };
  console.log('gate registered, expects origin:', trusted);
  console.log('payload gate passes:', forged?.type === 'selection' && typeof forged?.id === 'number');
}

What to watch for

  • Everything it calls is documented as part of the language core.
  • A browser is the runtime here: document, window are not available in Node.
  • The guard event.origin !== trusted exits before anything else runs using return when its condition holds.

Using it

Node prints only the DOM unavailable in this runtime fallback; a browser run prints gate registered, expects origin: with the trusted URL, then payload gate passes: true.

Key statements

window.addEventListener('message', (event) => {
  if (event.origin !== trusted) return;
  if (event.data?.type !== 'selection') return;
  document.title = 'picked ' + event.data.id;
});

Interactive Tools for This Topic

FAQ

Does postMessage Validates The Sender Origin run in plain Node.js?
No — it touches `document` and `window`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.