Skip to content

Latest commit

Β 

History

History
48 lines (33 loc) Β· 1.95 KB

require-post-message-target-origin.md

File metadata and controls

48 lines (33 loc) Β· 1.95 KB

require-post-message-target-origin

πŸ“ Enforce using the targetOrigin argument with window.postMessage().

🚫 Disabled by default.

πŸ’‘ This rule is manually fixable by editor suggestions.

Specifying the targetOrigin argument with window.postMessage() is a security best practice. It ensures that sensitive messages are only delivered to the intended recipient, preventing accidentally sending data to a window with an unexpected origin due to navigation or redirects.

When TypeScript type information is available, this rule ignores methods whose call signatures have no targetOrigin parameter, such as Worker#postMessage(), MessagePort#postMessage(), and BroadcastChannel#postMessage().

Without type information, or when any possible method type has no known call signatures (such as any or Function), this rule cannot distinguish between window.postMessage() and other .postMessage() methods.

Examples

// ❌ - Missing targetOrigin, message could be intercepted
window.postMessage(sensitiveData);

// βœ… - Explicit target origin prevents security issues
window.postMessage(sensitiveData, 'https://trusted-domain.com');
// ❌
window.postMessage({token: authToken});

// βœ… - Always specify the target origin
window.postMessage({token: authToken}, 'https://api.example.com');
// βœ… - '*' is acceptable when sending non-sensitive public data
window.postMessage({publicData: 'hello'}, '*');
// ❌ - Sending to iframe without specifying origin
const iframe = document.querySelector('iframe');
iframe.contentWindow.postMessage(data);

// βœ… - Specify the exact origin you expect
iframe.contentWindow.postMessage(data, 'https://expected-iframe-origin.com');