JavaScript call from flex application


 

JavaScript call from flex application

In flex application, you may have called function defined in action script

In flex application, you may have called function defined in action script

A JavaScript call from flex application

In flex application, you may have called function defined in action script. Sometimes you may need to call a javascript function defined in html file where your flex file is embed. For this purpose, ExternalInterface api is used which makes it possible to communicate between ActionScript and flash player container like html.

 

<?xml version="1.0" encoding="utf-8"?>

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">

<mx:Script>

<![CDATA[

import mx.controls.Alert;

import flash.external.*; 

public var _brandProduct1:Object = {brand: "Sony", product: "Sony Bravia S Series LCD TV, KLV-26S400A", price: "Rs.34,900"};

public var _brandProduct2:Object = {brand: "Sony", product: "Sony Bravia S Series LCD TV, KLV-40S310A", price: "Rs.77,990"};  

private function callJS(brandProduct:Object):void {

if (ExternalInterface.available){

ExternalInterface.call("displayBrandProduct", brandProduct); 

}else {

Alert.show("Failed.");

}

}

]]>

</mx:Script>

<mx:Button label="Get 1st Product Info" click="callJS(_brandProduct1)"/>

<mx:Button label="Get 2nd Product Info" click="callJS(_brandProduct2)"/>

</mx:Application>

The property 'available' in ExternalInterface is used to check whether the flash player is in a container ie. in html or not. The call() method is used to call the javascript function. The first argument takes the name of the javascript function and then pass zero or more arguments.

Now you need to define javascript function in html file where swf file is embed.

<script language="javascript">

function displayBrandProduct(brandProduct){

if(brandProduct != null){

alert("Brand: "+brandProduct.brand+"\nProduct: "+brandProduct.product+"\nPrice: "+brandProduct.price);

}else{

0

alert("Please select a person, or maybe I screwed up.");

}

}

1

</script>

Running the application will display output like below:

2

Click on the first button, a javascript alert box opens as given below:

Click on the second button, a javascript alert box opens as given below: 

3

Ads