unicorn/require-post-message-target-origin
Require the targetOrigin argument of window.postMessage()
Without targetOrigin, window.postMessage() only delivers the message if the other window has the same origin as yours. A message to an iframe or a popup on another origin is dropped without an error. Naming the origin also makes sure the data only goes to the site you mean.
The rule only looks at the method name. It reports .postMessage() with exactly one argument on any object, except one that looks like a message port: port, port1, port2, messagePort, channel.port1, event.ports[0].
Configure#
Off by default. To turn it on:
[lint.rules]
"unicorn/require-post-message-target-origin" = "error" # or "warn"Examples#
window.parent.postMessage({ type: "ready" })Missing the targetOrigin argument.;
frame.contentWindow.postMessage(token)Missing the targetOrigin argument.;window.parent.postMessage({ type: "ready" }, "https://app.example.com");
frame.contentWindow.postMessage(token, window.location.origin);
channel.port1.postMessage({ type: "ready" });When not to use it#
Worker, BroadcastChannel and ServiceWorker also have a postMessage() method, and theirs doesn't take an origin. The rule can't tell them apart from a window, so it reports them too:
const worker = new Worker("./resize.js");
worker.postMessage(image)Missing the targetOrigin argument.;If your code talks to workers a lot, this rule gets in the way.