postMessage Validates The Sender Origin
Gate window messages by event.origin before touching data: unmatched senders are dropped and payload shape is verified independently.
Code
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,windoware not available in Node. - The guard
event.origin !== trustedexits before anything else runs usingreturnwhen 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
Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.CSP Header BuilderBuild a Content-Security-Policy header from per-directive sources, skipping empty ones and rejecting a blanket wildcard.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.