Loading and Running JavaScript function at runtime with ExternalInterface.
The only mandatory thing is the swf should run in the browsers that support NPRuntime.
Which almost all browsers support.
Please find the xml and AS3 Code below.
::XML
<?xml version=”1.0″ ?>
<data>
<createNamespace_js>
<script>
<![CDATA[
function(){
// Creates a global namespace called
// "Dojo" if one doesn't already exist.
// Here's one way to do this *safely*.
// If Dojo is a valid object of any type,
// including objects and functions, it will
// be left alone. If it doesn't exist, an
// exception is thrown, trapped, and
// "Dojo" is globally created.
try {
Dojo
}catch(e){
Dojo = new Object();
}
}
]]>
</script>
</createNamespace_js>
<addFunction_js>
<script>
<![CDATA[
function(){
var snafu = 'You said';
var exists = false;
// "Dojo" is a JavaScript library object
// that was created by another script,
// and exists globally.
// Just to be safe, though, we make sure
// it exists before writing to it, otherwise
// an exception is thrown.
try {
Dojo;
exists = true;
} catch(e) {
exists = false;
}
if(exists){
Dojo.myVar = 'foo';
Dojo.myFunction = function (str) {
alert(snafu + ":" + str);
}
};
}
]]>
</script>
</addFunction_js>
<callFunction_js>
<script>
<![CDATA[
function(txt, txt2){
txt = txt + " World, " + txt2;
Dojo.myFunction(txt);
}
]]>
</script>
</callFunction_js>
</data>
:: AS3
import flash.external.ExternalInterface;
var createNamespace_js:XML ;
var addFunction_js :XML ;;
var callFunction_js :XML ;;
var functionArray:Array = ["createNamespace_js","addFunction_js","callFunction_js"];
var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.TEXT;
loader.addEventListener(Event.COMPLETE, onLoadXML);
function callFunctions():void
{
// calling virtual function to create global object DOjo;
ExternalInterface.call(createNamespace_js);
// calling virtual function to add function and var to global object DOjo;
ExternalInterface.call(addFunction_js);
// calling Dojo.myFunction with 1 parameter;
ExternalInterface.call(”Dojo.myFunction”, “First call to DOjo.myFunction
“);
// calling virtual function which internally alls the Dojo.myFunction ; with 2 parameters
ExternalInterface.call(callFunction_js, “Hello”, “from virtual function ” );
}
function onLoadXML(ev:Event){
try{
//Convert the downloaded text into an XML
var myXML:XML = new XML(ev.target.data)
var list:XMLList = myXML.children();
for(var i=0; i<list.length(); i++){
var temp:XML = new XML(list[i]);
for( var j in functionArray){
if(functionArray[j] == temp.name()){
this[functionArray[j]] = new XML(temp.script);
}
}
}
} catch (e:TypeError){
trace(”Could not parse the XML”)
trace(e.message)
}
callFunctions();
}
loader.load(new URLRequest(”sample.xml”));
stop()
