Apart from the general rule that eval
should be avoided if possible, your current code is not secure.
Cross-document messaging is supposed to be a safe technique for cross-origin communication. The most important aspect here is respecting the origins: The sender can decide to which documents of which origin a message may be sent and a receiver can decide of which origins it may accept messages from.
But in your case your sender neither specify the recipient origin nor does the recipient check the sender origin. This is a security weakness as either your sender can send messages to a wrong recipient (your frame’s document changes) or your recipient accepts messages with potential malicious code from a wrong sender (your document is embedded in a malicious page).
So to make your cross-document messaging secure, always specify the sender’s origin within the postMessage
call:
otherWindow.postMessage(message, "http://example.org:8080");
And always check the origin when receiving a message:
function receiveMessage(event) {
if (event.origin !== "http://example.org:8080") return;
// ...
}
window.addEventListener("message", receiveMessage, false);
If you’re communicating within the same origin, you can use window.location.origin
:
// sender
otherWindow.postMessage(message, window.location.origin);
// recipient
if (event.origin !== window.location.origin) return;
As window.location.origin
seems to be available in WebKit only, here’s a workaround:
if (!window.location.hasOwnProperty("origin")) {
window.location.origin = window.location.protocol + "//" + window.location.host;
}