I’m sending the code of a javascript function that is defined in the parent document:
var fn = function(){
// code here that is going to be eval'd
};
$('#iframe').get(0).contentWindow.postMessage(encodeURI(fn.toString()));
to be evaluated in the iframe:
$(window).bind('message', function(e){
eval('(' + decodeURI(e.originalEvent.data) + ')();');
});
The reason I’m doing this is because I can manage the code easier, because this way all the js is in one file 🙂
But is it safe?
The only one who can modify the code is the same person on which’s computer the code gets evaluated, right?
Apart from the general rule that
evalshould 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
postMessagecall:And always check the origin when receiving a message:
If you’re communicating within the same origin, you can use
window.location.origin:As
window.location.originseems to be available in WebKit only, here’s a workaround: