Call Actionscript Functions By Javascript

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

I wrote a tutorial “Call Javascript Functions From Flash and Flex” about how flash calls javascript function. I think it is necessary to write another tutorial about how the javascript function calls actionscript function inside flash. See the example below:

Javascript Code

<script type="text/javascript">// <!&#91;CDATA&#91;
 	function getFlashMovie(movieName) {
    		var isIE = navigator.appName.indexOf("Microsoft") != -1;
 		return (isIE) ? window&#91;movieName&#93; : document&#91;movieName&#93;;

 	function CallFlashFun() {
 		var textarea = document.getElementById("jsMsg");
 		var flashObj = getFlashMovie("flashObject");
// &#93;&#93;></script>
<object id="flashObject" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="290" height="100">
    <param name="movie" value="javascriptcallflash.swf" />
    <param name="quality" value="high" />
    <param name="allowScriptAccess" value="always" />

    <embed type="application/x-shockwave-flash" width="100%" height="100%" src="javascriptcallflash.swf" name="flashObject" wmode="transparent" allowscriptaccess="always"></embed>

Function getFlashMovie(movieName) will return the flash object. There is one point needed to mension that document[movieName] also works in IE9. And function asFunction(String param) is define in the flash;

Actionscript Code

function showJSMsg(msg:String):void {
(jsMsg as TextArea).htmlText = msg;

ExternalInterface.addCallback("asFunction", showJSMsg);

This Actionscript code is very simple. It just uses ExternalInterface.addCallback to define a javascript function interface “asFunction”, so that the outside javascript can call asFunction function.

Download Source Code

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

Tagged with:  

6 Responses to “Call Actionscript Functions By Javascript”

  1. Chianna says:

    I love reading these articles beacuse they’re short but informative.

  2. Coralee says:

    Ab fab my godoly man.

  3. Michelle Barajas says:

    Hi, I’m desperately trying to make this code work. I see that on your website, it works perfectly–but when I download, it doesn’t go through. Any assistance possible? I have spent all my waking day trying to find something that will work; I do believe you are my last hope.

    • James Liu says:

      I publish all my source code in the post. If you just follow the code, it should work properly. If you can provide some debug message, it will be more helpful.


  4. ThreeBean says:

    You cannot run it local on your machine and expect it to work. Push it up to a server and test.

Leave a Reply

Free WordPress Themes

WordPress Blog