Javascript and Flex Communication
11 04 2008A couple days a go I was writing a quick flex app at work and it became necessary for me to be able communicate between javascript and flex, that is, making javascript calls from flex and making flex calls from javascript. After a bit of research, I found that it is a pretty easy thing to do. To make it easier to see what is going on I’m splitting this up into two separate examples.
Making javascript calls from flex:
<?xml version="1.0" encoding="iso-8859-1"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" width="300" height="86" layout="absolute" > <mx:Script> <![CDATA[ import flash.external.*; function buttonClicked():void { ExternalInterface.call("alert", userInputField.text); } ]]> </mx:Script> <mx:TextInput id="userInputField" x="20" y="28" width="191"/> <mx:Button label="JS Alert" click="buttonClicked()" x="219" y="28"/> </mx:Application>
The above example makes a simple call to the javascript function “alert” and passes the text in the text field as an argument to the alert function. To pass more than one argument simply just add them as additional arguments to the ExternalInterface.call() method. Example: ExternalInterface.call(”myJsFunction”, “arg1″, “arg2″);
Making flex calls from javascript:
<?xml version="1.0" encoding="iso-8859-1"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" width="300" height="86" layout="absolute" creationComplete="init()" > <mx:Script> <![CDATA[ import flash.external.*; function init():void { ExternalInterface.addCallback("setTextField", setTextField); } function setTextField(userInput:String):void { userInputField.text = userInput; } ]]> </mx:Script> <mx:TextInput id="userInputField" x="20" y="28" width="191"/> </mx:Application>
var flexApp; if (navigator.userAgent.indexOf("MSIE") != -1) { flexApp = window[flexElementObjectId]; } else { flexApp = document[flexElementObjectId]; } flexApp.setTextField("Hello World");
This example invokes a flex function from javascript. As you may have noticed this is relatively simple, all you need to do is add a an external callback within flex and make a call to the DOM object from Javascript.


Hi
One small correction, In case of IE7 window[flexElementObjectId] doenot return any value.
So use document[flexElementObjectId] for IE7.