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 flash.events.MouseEvent; 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) { ExternalInterface.call("callJavascriptFunction", parameter); } else { ExternalInterface.call("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 ExternalInterface.call(javascript_Function_Name, 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">// <![CDATA[ function callJavascriptFunction(fcontent) { if(fcontent == null) { alert('Flash Button has nothing to say.'); } else { alert('Flash Button say: ' + fcontent); } } // ]]></script>
Download Source Code
If you want to download the try the example, please click here;
Articels like this make life so much simpler.
All of these atricles have saved me a lot of headaches.