The Flex Application can communicate with the JavaScript running on the browser asynchronously. The Flex can call a function in JavaScript meanwhile JavaScript can call a function in Flex. Let us see how it can be achieved.
The Action Script interface ‘ExternalInterface’ provides methods to communicate with the JavaScript
In your flex IDE create a new flex project,
Case 1: Calling JavaScript form Flex
JavaScript side:
Under the project root directory some subdirectories are exist.
Such as
- bin-debug
- html-template
- libs
- src
Now open the ‘html-template’ subdirectory under this open the ‘index.template.html’ file to edit. Within <head> </head> tags define a function that that is called from the Flex application.
<script language=”JavaScript” type=”text/javascript”>
function jsFunction(flex_msg)
{
alert(“JavaScript : Hi Flex I received your message “+flex_msg);
}
</script>
Flex side:
Now open ’ .mxml’ file type the code below that calls the function in JavaScript.
<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml” layout=”absolute” >
<mx:Script>
<![CDATA[
import mx.controls.Alert;
import flash.external.ExternalInterface;
private function accessJavaScipt():void
{
if(ExternalInterface.available)
{
ExternalInterface.call("jsFunction",”Hii a message to you”);
}
}
]]>
</mx:Script>
<mx:Button y=”171″ label=”Call JavaScript” horizontalCenter=”0″ click=”accessJavaScipt()”/>
</mx:Application>
Case 2: Calling Flex from JavaScript
Flex side:
The Action Script API ExternalInterface interface allows to register call back functions that are called from the JavaScript. Define all callback functions that are called from the javascript in flex application creationComplete event.
private function creationCompleteHandler():void
{
if(ExternalInterface.available)
{
ExternalInterface.addCallback(“flexFunction”, javascriptEventsHandler);
}
}
private function javascriptEventsHandler():void
{
Alert.show(“Flex : Hi JavaScript”);
}
JavaScript Side
open the index.template.html file and define a html button tag as below.
<input type=”button” onClick=’callFlex()” value=”call Flex” />
In script block define handler function ‘callFlex()’ like below
<script language=”JavaScript” type=”text/javascript”>
function callFlex()
{
$ {application}.flexFunction();
}
<script>
Now execute the application and click on the ‘callFlex’ button the flex application responds with alert message.
Now the flex application movie object is browser specific to get instance of browser define a function that will return the movie object reference as browser specific.
in Javascript define function as
indsa
function getFlexMovieRef(appName)
{
if (navigator.appName.indexOf (“Microsoft”) !=-1) {
return window[appName];
} else {
return document[appName];
}
}
this function now return a object will call callback functions in action script .
getFlexMovieRef(“${application}”).flexFunction();