How do you call an actionscript function from a html page and viceversa. How to you access the actionscript variable function from an HTML page in actionscript.

By | December 26, 2010

The following code helps you to do this.
Save the following  code as am .mxml file

<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml"
    layout="absolute" creationComplete="init()">
    <mx:Script>
    <![CDATA[
        private var calledFromJSHandlerFunction:Function = calledFromJSHandler;
        private function init():void{
            html.addEventListener(Event.HTML_DOM_INITIALIZE, domInitialized);
            html.location = "start.html";
        }
        private function domInitialized(event:Event):void{
            html.htmlLoader.window.calledFromJSHandlerFunction = calledFromJSHandlerFunction;
        }
        private function calledFromJSHandler():void {
            mx.controls.Alert.show("ActionScript called from JavaScript", "Alert");
        }
        private function doHTMLAlert( ):void {
            html.htmlLoader.window.calledFromAS();
        }
    ]]>
    </mx:Script>
    <mx:Button id="alertBtn" label="Call JavaScript from ActionScript"
        click="doHTMLAlert()" x="137" y="10"/>
    <mx:HTML id="html" x="137" y="40" width="339"/>
    <mx:Label x="10" y="12" text="Normal MXML Button"/>
    <mx:Label x="28" y="38" text="HTML component"/>
</mx:WindowedApplication>

The html file start.html

<html>
    <script language="Javascript">
        function calledFromAS() {
            alert('Hello from ActionScript');
        }
        </script>
    <body>
        <input type="button"
            value="Call ActionScript from JavaScript"
            onclick="calledFromJSHandlerFunction()" />
        <br />
        <input type="button"
            value="Normal JavaScriptAlert"
            onclick="alert('Hello from JavaScript')">
    </body>
</html>

Leave a Reply

Your email address will not be published. Required fields are marked *