Injecting and calling JS functions from within flash using external

JS injection

I recently encountered a unique requirement in one of my projects, triggering the loading of a page in the background (outside of flash, using Ajax) from within flash.
Often you cannot rely on JS functions to be available, you could load public libraries (Jquery or equivalent) or inject your own functions to the DOM, I chose to inject my own.

This is how you do it:

1) import the external class.

import flash.external.ExternalInterface;

2) declare a constant variable with all the JS functions:

private const script_js :XML =
<script>
<![CDATA[
function() {
AJXFNC = {
ajaxFunction:function(_url){

var ajaxRequest;
try{
// Opera 8.0+, Firefox, Safari, Chrome
ajaxRequest = new XMLHttpRequest();
ajaxRequest.open("GET", _url, true);
ajaxRequest.send(null);

} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
ajaxRequest.open("GET", _url, true);
ajaxRequest.send();

} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
ajaxRequest.open("GET", _url, true);
ajaxRequest.send();

} catch (e){
// Something went wrong
return false;
}
}
}
}

}
}
]]>
</script>;

3) inject the JS to DOM:

try {
if( ExternalInterface.available )ExternalInterface.call( script_js );
} catch( error:Error ) {
trace("ExternalInterface is not available");
}

4) call a function:

ExternalInterface.call( "AJXFNC.ajaxFunction", "http://www.google.com" );

Sweet isn’t it?

2 thoughts on “Injecting and calling JS functions from within flash using external”

Leave a Reply

Your email address will not be published. Required fields are marked *