Thursday, January 31, 2008

Flash Hacks: Call Arbitrary JavaScript!

In the past I've been annoyed by the lack of HTTP header access in Flash. Turns out there are some hacks you can do to get around it. Let's say you want the URL of the web page that loaded the SWF. This would be the referrer of the HTTP request that loaded the SWF. Flash should provide access to that, but it doesn't because some browsers don't provide it this info. That's ok, you can get to it:
var hostPageUrl:String = ExternalInterface.call("window.location.href.toString");

That's right, you can "call" a JavaScript expression, not just a function defined on the page. Of course the key is that everything in JavaScript (and in ActionScript too) is a function. So any JavaScript expression is a function and thus invokable via ExternalInterface. You can see where this is going! Let's say you want the query string of the host page's URL:
var queryString:String = ExternalInterface.call("window.location.search.toString");

This will give you something like "?param=value&foo=bar..." What about the referrer of that page? 2EZ:
var referrer:String = ExternalInterface.call("document.referrer");
This is a classic case of Too Much Information, really. You are able to execute arbitrary JavaScript, ExternalInterface acts like an eval(). So you can do arbitrary badness like modify the DOM. You can also access cookies (document.cookie).

Of course the key to all of this is script access. The SWF needs to have it. If the SWF is from the same domain as the web page, it gets this by default. If not, then you need to set allowScriptAccess="always". That gives the SWF the keys to the kingdom, if you will. Of course you could use an IFrame for the SWF and sandbox it in.

1 comment:

Anonymous said...

Were you able to get the arbitrary JS calls to work as you outlined? I don't think that works. I think instead that you would need to call the JS functions as:

ExternalInterface.call( "function(){return document.location.href;}" );

as referenced from here:

http://viconflex.blogspot.com/2007/04/closer-look-at-iframes-and.html