π 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.
// β - 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');