unicorn/require-post-message-target-origin

Require the targetOrigin argument of window.postMessage()

has suggestions

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:

bunfig.toml
[lint.rules]
"unicorn/require-post-message-target-origin" = "error" # or "warn"

Examples#

example.js2 problems
window.parent.postMessage({ type: "ready" });
frame.contentWindow.postMessage(token);
example.jsNo problems
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:

example.js1 problem
const worker = new Worker("./resize.js");
worker.postMessage(image);

If your code talks to workers a lot, this rule gets in the way.