Maybe you’ve made a deal with a partner website, or you’re just loading a page from another server. The point is: You’ve got an IFrame on your page coming from another domain.
All is well (except for Google, they don’t like iframes) untill you want some client-side interaction coming from that page.
But now you’ve reached the point where you want some client-side interaction from that IFrame. “Great!” you say. I’ll just put JS in the IFrame, and I’ll be fine. But hold your horses cowboy, there’s 2 things stopping you as a great developer from doing so:
Don’t have you JS scattered, have it nice and organised, centralized
You’re visually constrained to the IFrame
So how do we execute JS on the parent frame?
Directly from the IFrame? You can’t! Sandbox specifications say you can’t call functions defined in pages coming from another domain (kind of like loading JSON/Ajax from another domain).
But in that problem also lies the solution: just load a Proxy page from the other server!
Let me make myself a bit more clear through some Graphs:
Normally, you’de have 2 pages, page A contains an Iframe to page B:
Now we’re introducting a Proxy page, on the same server as page A. Page B contains a IFrame to the proxy page: All Done! Now you can execute JS, like so:
The Code!
So how do we do it? Here you go! index.html (on your server)
<html><head><scripttype="text/javascript">
function alertme(str)
{
alert("String: " + str);
}
</script></head><body><iframesrc="http://yourpartner.com/iframe.htm"></iframe></body></html>
proxy.html (on your server)
<html><head><scripttype="text/javascript">
function gup( name )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
eval("top."+gup("execute"));
</script></head></html>
And finally! iframe.html (on any other server)
<html><head></head><body>
Hi There!
<iframesrc="http://yourserver.com/proxy.html?execute=alertme(123);"></iframe></body></html>
What you did there, I don’t quite see it
In the page on the other server, I pass a function call as an argument to my proxy.
My proxy then gets this function out of the parameter, and executes it through eval()!
Warning
Handle with care, allowing anyone to simply execute JS on/from your server through a parameter just opens up a whole new spectrum of XSS attacks.
That sandbox was created for a reason!