Call a function in FLEX from JavaScript
Submitted by softking on Thu, 06/12/2008 - 09:48
Sometimes you need to call a function that is defined in your Flex application from the JavaScript code that wraps it.
In order to do so you have to define a callback function inside the Flex application and declare it using the ExternalInterface class.
So first we define the function that will be called:
public function onMsgFromJS(message:String):void{
Alert.show(message);
}Then somewhere in your code, maybe in the init function you declare that function as a callback function
public function init():void{
ExternalInterface.addCallback("onMsgFromJS",onMsgFromJS);
}Then you can start working on the JavaScript side. In your html file add a JavaScript block with the following code:
function thisMovie(movieName) {
// IE and Netscape refer to the movie object differently.
// This function returns the appropriate syntax depending on the browser.
if (navigator.appName.indexOf ("Microsoft") !=-1) {
return window[movieName];
} else {
return window.document[movieName];
}
}
//this function would call a flash/flex function.
function callFlex()
{
//Get the reference so activeX or Plugin. flexApp is id/name of OBJECT/EMBED tags
var flashObject = thisMovie("flexApp");
flashObject.onMsgFromJS("Hello from JavaScript");
}Now you can add calls to the function "callFlex"
like this:
<input type="button" value="Call Flex" onclick="callFlex();" />