Code example JavaScript - Avoid use of unrestricted target

Code examples


Noncompliant code

When sending message:

var iframe = document.getElementById("testiframe");
iframe.contentWindow.postMessage("secret", "*"); // Noncompliant: * is used

When receiving message:

window.addEventListener("message", function(event) { // Noncompliant: no checks are done on the origin property.
console.log(event.data);
});

Compliant code

When sending message:

var iframe = document.getElementById("testsecureiframe");
iframe.contentWindow.postMessage("hello", "https://secure.example.com"); // Compliant

When receiving message:

window.addEventListener("message", function(event) {
if (event.origin !== "http://example.org") // Compliant
return;

});

Last modified on Mar 19, 2021