Home > ActionScript 3, Flex > Calling Flex Methods From JavaScript

Calling Flex Methods From JavaScript

If you want to call methods inside of your Flex application from javascript all you have to do is a couple of simple steps. First you have to add the external interface to you flex application:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="creationComplete()">
	<mx:Script>
		<![CDATA[
			import mx.controls.Alert;

			private function creationComplete():void
			{
				ExternalInterface.addCallback("doCall", myCall);
			}

			private function myCall(message:String):void
			{
				Alert.show("Did Call: " + message);
			}
		]]>
	</mx:Script>
</mx:Application>

Then, from JavaScript you need to access the movie and then call the method that was created as an external interface. You can even pass in parameters:

function getMovie(movieName)
{
    if (navigator.appName.indexOf("Microsoft") != -1) {
        return window[movieName];
    } else {
        return document[movieName];
    }
}

function doCall() {
	getMovie("[Your Movie Name Here]").doCall("Hello World!");
}
Categories: ActionScript 3, Flex
  1. sam
    October 27, 2009 at 3:31 pm | #1

    function doCall() { 11.
    getMovie(“[Your Movie Name Here]“).doCall(“Hello World!”); 12.}
    .
    .
    .
    change it to ….
    .
    .
    function doCall() { 11.
    getMovie(“[Your Movie Name Here]“).myCall(“Hello World!”); 12.}

  2. October 27, 2009 at 3:34 pm | #2

    Actually, the way I have it is correct because I’m doing this:

    ExternalInterface.addCallback(“doCall”, myCall);

    doCall is the external call available to JavaScript. myCall is internal to the Flex application and isn’t visible to JavaScript.

    -Ben

  1. No trackbacks yet.