Call Javascript Functions From Flash and Flex

On April 13, 2011, in Flash Flex AIR, by James Liu

Today, I try to call a Javascript function from flash, and it take me a long time to write the actionscript code to solve it. I think it’s necessary to post it online to help other peoples. In this tutorial, I just put a flash button in stage, and then call the javascript function when user clicks this button. If you want to call javascript function from flex, u can use the actionscript code in the same way.

Call Javascript Function From Flash Example

Actionscript Code

At beginning, we create a flash file, and put one Button and one TextInput component on the stage. Then we add the following actionscript code:

import fl.controls.TextInput;
flashButton.addEventListener(MouseEvent.CLICK, callJavascriptFunction);

function callJavascriptFunction(event:MouseEvent):void {
    var parameter:String = (textInputBox as TextInput).text;
    if(parameter.length > 0) {"callJavascriptFunction", parameter);
    } else {"callJavascriptFunction", null);

We add a MouseEvent.CLICK event on the flash button, so that it will trigger the listener function callJavascriptFunction(event:MouseEvent) when user clicks it. In this function, it will call, parameters) to invoke the outside javascript functions; Here we will check the TextInput component textInputBox attribute text. If the TextInput is empty, it will pass the javascript function with null. Otherwise, it will pass the text content as a parameter.

Javascript Code

In the html page, we just need to add following Javascript code:

<script type="text/javascript">// <!&#91;CDATA&#91;
 	function callJavascriptFunction(fcontent) {
 		if(fcontent == null) {
 			alert('Flash Button has nothing to say.');
 		} else {
 			alert('Flash Button say: ' + fcontent);
// &#93;&#93;></script>

Download Source Code

If you want to download the try the example, please click here;

Tagged with:  

2 Responses to “Call Javascript Functions From Flash and Flex”

  1. Caelyn says:

    Articels like this make life so much simpler.

  2. Jaxon says:

    All of these atricles have saved me a lot of headaches.

Leave a Reply


WordPress Blog