π 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.
This rule cannot distinguish between window.postMessage() and other calls like Worker#postMessage(), MessagePort#postMessage(), Client#postMessage(), and BroadcastChannel#postMessage(), which don't have a targetOrigin parameter.
// β - 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');