Browsers allow message exchanges between Window objects of
different origins.
Because any window can send or receive messages from another window, it is important to verify the sender’s/receiver’s identity:
- When sending a message with the postMessage method, the identity’s receiver should be defined (the wildcard keyword (
*
) should not
be used).
- When receiving a message with a message event, the sender’s identity should be verified using the origin and possibly source properties.
Noncompliant Code Example
When sending a message:
var iframe = document.getElementById("testiframe");
iframe.contentWindow.postMessage("secret", "*"); // Noncompliant: * is used
When receiving a message:
window.addEventListener("message", function(event) { // Noncompliant: no checks are done on the origin property.
console.log(event.data);
});
Compliant Solution
When sending a message:
var iframe = document.getElementById("testsecureiframe");
iframe.contentWindow.postMessage("hello", "https://secure.example.com"); // Compliant
When receiving a message:
window.addEventListener("message", function(event) {
if (event.origin !== "http://example.org") // Compliant
return;
console.log(event.data)
});
See