Saturday, April 17, 2010

Flex 3: Calling JavaScript from Flex

It is possible to communicate with the javascript functions reside in the html page from Flex. Flex library has an ExternalInterface class which allow us to communicate with Flex and javaScript and vice versa.

In this tutorial I will explain how you can communicate. You can call javaScript function which has no parameter, which has parameters and function which is returning values. I will cover function which will receive parameter in string format and returns the plain string.

To start with, First create a flex project in the Builder. First we will create a javaScript function in the html page and then we will call that from the Flex application. Open your index.template.html form {project}/html-template/ folder. In this html page add following code just before the <noscript> tag.

<script language="JavaScript" type="text/javascript">

function flexTojavaScript(fromFlex)
return 'Returning from JavaScript to Flex';

In the above code I have created the Script tag and within that I have created a function named 'flexTojavaScript' which will receive a parameter named 'fromFlex'. This function will return plain text.

That's it, we are done with the changes in html page.

Now we will move to the flex application mxml. In this mxml, I have created a button which will call the clickHandler on clicking on it. From the click handler I have called the javascript function using ExternalInterface class. The value returned from the javascript is stored in the returnFromJavaScript variable.

private function clickHandler():void
returnFromJavaScript ="flexTojavaScript", "This is called from Flex");
ExternalInterface class has static method named 'call'. using this function we can call the javaScript function. In this function you will find two parameter, first parameter is the name of the javaScript function as a string. You can also send the parameters. In the above code we are sending plain string to javaScript. As mention above the function is javaScript is returning string. Which we are storing in the application local variable. In this application I have crated the text which will show up the return value of javaScript function.

That's it We are done with the changes. Just build your project and click on the button. You will find that javaScript alert will appear. Which will have the parameter text what we have sent from the Flex. On Clicking OK button of the alert prompt. You will find that the value which is returned from the javaScript will populate below the button.

This is very simple method using which we can call the javaScript function from the Flex.

I hope this will help you.

In my next tutorial I will explain the revers of this, i.e. Calling Flex function from javaScript.


Post a Comment