天天看點

SWF(ActionScript3.0)與JavaScipt(JS)通信示例

今天花了一些時間整理出來了Swf 檔案與JavaScript通信的示例,在此貼出供大家參考。

在ActionScript3.0與JavaScipt通信的時候需要用到ExternalInterface類。

“ExternalInterface”類是外部API,在ActionScript和FlashPlayer的容器之間實作直接通訊的應用程式程式設計接口,例如,含有JavaScript的HTML頁。推薦對所有JavaScript與ActionScript之間的通信使用ExternalInterface。

在HTML頁中使用JavaScript,可以調用FlashPlayer中的ActionScript函數。ActionScript函數可以傳回一個值,JavaScript會立即接收它作為該調用的傳回值。

此功能替代了較舊的fscommand()方法。“——摘自<ActionScript3.0語言群組件參考-ExternalInterface>.

ExternalInterface

一個重要屬性:available:Boolean見下邊代碼的粗體顯示“point1”

[static][read-only]訓示此播放器是否位于提供外部接口的容器中。

注意:将ExternalAPI與HTML一起使用時,應始終在嘗試調用任何JavaScript方法之前先檢查HTML是否已完全加載。

兩個重要方法:

1、addCallback(functionName:String,closure:Function):void見下邊代碼的粗體顯示“point2”

[static]将ActionScript方法注冊為可從容器調用。

SecurityError&mdash包含環境屬于調用代碼無權通路的安全沙箱。修正此問題:

在包含HTML頁中的SWF檔案的<object>标簽中,設定以下參數:

<paramname="allowScriptAccess"value="always"/>

在SWF檔案中,添加以下ActionScript:

flash.system.Security.allowDomain(sourceDomain)

2、call(functionName:String,...arguments):*見下邊代碼的粗體顯示“point3”

[static]調用由FlashPlayer容器公開的函數,不傳遞參數或傳遞多個參數。

//------------------------------ExternalInterfaceExample.as------------------

package ActionScript

{

    import flash.display.Sprite;

    import flash.events.*;

    import flash.external.ExternalInterface;

    import flash.filters.GlowFilter;

    import flash.text.TextField;

    import flash.text.TextFieldAutoSize;

    import flash.text.TextFieldType;

    import flash.utils.Timer;

    publicclass ExternalInterfaceExample extends Sprite

    {

       privatevar input:TextField;

       privatevar output:TextField;

       privatevar sendBtn:Sprite;

       publicfunction ExternalInterfaceExample() {

           //-----------------初始化UI------------start--------------

           input = new TextField();

           input.type = TextFieldType.INPUT;

           input.background = true;

           input.border = true;

           input.borderColor = 0x7f9db9;

           input.width = 274;

           input.height = 20;

           input.x = 8;

           input.y = 16;

           addChild(input);

           sendBtn = new Sprite();

           sendBtn.mouseEnabled = true;

           sendBtn.x = input.width + 8 + 6;

           sendBtn.y = 16;

           sendBtn.graphics.lineStyle(1, 0x7f9db9, 1);

           sendBtn.graphics.beginFill(0xCCCCCC);

           sendBtn.graphics.drawRoundRect(0, 0, 140, 20, 0, 0);

           sendBtn.graphics.endFill();

           //添加發送事件

           sendBtn.addEventListener(MouseEvent.CLICK, clickHandler);

           addChild(sendBtn);

           var label : TextField = new TextField();

           label.text = "發送資料到JS";

           label.autoSize = TextFieldAutoSize.LEFT;

           label.x = sendBtn.x+ Math.round((sendBtn.width - label.width)/2);

           label.y = sendBtn.y;

           label.selectable = false;

           label.mouseEnabled = false;

           addChild(label);                  

           this.graphics.lineStyle(1, 0x7f9db9, 1);

           this.graphics.moveTo(8, 40);

           this.graphics.lineTo(428, 40);

           this.graphics.lineTo(428, 203);

           this.graphics.lineTo(8, 203);

           this.graphics.lineTo(8, 40);

           output = new TextField();

           output.y = 40;

           output.x = 10;

           output.width = 420;

           output.height = 160;

           output.multiline = true;

           output.wordWrap = true;

           output.textColor = 0x00ff00;

           output.filters = [new GlowFilter(0x000000, 0.8, 2, 2, 8, 3)];

           output.text = "初始化...\n";

           addChild(output);

           //-----------------初始化UI---------end-----------------

           //訓示此播放器是否位于提供外部接口的容器中。如果外部接口可用,則此屬性為 true;否則,為 false。

           if (ExternalInterface.available) {     //point 1

              try {

                  //對JavaScript開放一個方法;

                  ExternalInterface.addCallback("sendToActionScript", receivedFromJavaScript);             //point 2

                  if (checkJavaScriptReady()) {

                     output.appendText("JavaScript is ready.\n");

                  } else {

                     //如果JavaScript is not ready,建立一定時器,沒0.1秒檢測一次,直至JavaScript is ready;

                     output.appendText("JavaScript is NOT ready, 0.1秒後重試.\n");

                     var readyTimer:Timer = new Timer(100, 0);

                     readyTimer.addEventListener(TimerEvent.TIMER, timerHandler);

                     readyTimer.start();

                  }

              } catch (error:SecurityError) {

                  output.appendText("A SecurityError occurred(安全錯誤): " + error.message + "\n");

              } catch (error:Error) {

                  output.appendText("An Error occurred(錯誤): " + error.message + "\n");

              }

           } else {

              output.appendText("External interface不可用。");

           }

       }

       privatefunction receivedFromJavaScript(value:String):void {              //point 2

           output.appendText("JavaScript 說: " + value + "\n");

       }

       privatefunction checkJavaScriptReady():Boolean {

           var isReady:Boolean = ExternalInterface.call("isReady");                     //point 3

           return isReady;

       }

       privatefunction timerHandler(event:TimerEvent):void {

           output.appendText("檢查 JavaScript 狀态...\n");

           if (checkJavaScriptReady()) {

              output.appendText("JavaScript is ready.\n");

              Timer(event.target).stop();

           }

       }

       privatefunction clickHandler(event:MouseEvent):void {

           if (ExternalInterface.available) {

              ExternalInterface.call("sendToJavaScript", input.text);                     //point 3

           }

       }

    }

}

//------------------------------------ExternalInterfaceExample.html---------------------------------------------

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<!-- saved from url=(0014)about:internet -->

<html xmlns="http://www.w3.org/1999/xhtml" xml:>        

    <!--

    Smart developers always View Source.

    This application was built using Adobe Flex, an open source framework

    for building rich Internet applications that get delivered via the

    Flash Player or to desktops via Adobe AIR.

    Learn more about Flex at http://flex.org

    // -->

    <head>

        <title>ExternalInterfaceExample示例</title>

        <meta name="google" value="notranslate">        

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

                   <!-- Include CSS to eliminate any default margins/padding and set the height of the html element and

                        the body element to 100%, because Firefox, or any Gecko based browser, interprets percentage as

                             the percentage of the height of its parent container, which has to be set explicitly.  Fix for

                             Firefox 3.6 focus border issues.  Initially, don't display flashContent div so it won't show

                             if JavaScript disabled.

                   -->

        <style type="text/css" media="screen">

                            html, body        { height:100%; }

                            body { margin:0; padding:0; overflow:auto; text-align:center;

                                   background-color: #ffffff; }  

                            object:focus { outline:none; }

                            #flashContent { display:none; }

        </style>

                   <!-- Enable Browser History by replacing useBrowserHistory tokens with two hyphens -->

        <!-- BEGIN Browser History required section -->

        <link rel="stylesheet" type="text/css" href="history/history.css" target="_blank" rel="external nofollow" />

        <script type="text/javascript" src="history/history.js"></script>

        <!-- END Browser History required section --> 

        <script type="text/javascript" src="swfobject.js"></script>

        <script type="text/javascript">

                    var jsReady = false;

         //暴露給ActionScript的方法

     function isReady() {

         return jsReady;

     }                                                                                                             // point 3

     function pageInit() {

         jsReady = true;

         document.forms["form1"].output.value += "\n" + "JavaScript is ready.\n";

     }

     function thisMovie(movieName) {

         if (navigator.appName.indexOf("Microsoft") != -1) {

             return window[movieName];

         } else {

             return document[movieName];

         }

     }

         //調用ActionScript暴露的方法sendToActionScript

     function sendToActionScript(value) {

         thisMovie("ExternalInterfaceExample").sendToActionScript(value);

     }

         //暴露給ActionScript的方法       

     function sendToJavaScript(value) {

         document.forms["form1"].output.value += "SWF 說: " + value + "\n";

     }       

<!-- For version detection, set to min. required Flash Player version, or 0 (or 0.0.0), for no version detection. -->

            var swfVersionStr = "10.0.0";

            <!-- To use express install, set to playerProductInstall.swf, otherwise the empty string. -->

            var xiSwfUrlStr = "playerProductInstall.swf";

            var flashvars = {};

            var params = {};

            params.quality = "high";

            params.bgcolor = "#ffffff";

            params.allowscriptaccess = "sameDomain";

            params.allowfullscreen = "true";

            var attributes = {};

            attributes.id = "ExternalInterfaceExample";

            attributes.name = "ExternalInterfaceExample";

            attributes.align = "middle";

            swfobject.embedSWF(

                "ExternalInterfaceExample.swf", "flashContent",

                "640", "340",

                swfVersionStr, xiSwfUrlStr,

                flashvars, params, attributes);

                            <!-- JavaScript enabled so display the flashContent div in case it is not replaced with a swf object. -->

                            swfobject.createCSS("#flashContent", "display:block;text-align:left;");       

        </script>

    </head>

    <body οnlοad="pageInit();">

        <!-- SWFObject's dynamic embed method replaces this alternative HTML content with Flash content when enough

                             JavaScript and Flash plug-in support is available. The div is initially hidden so that it doesn't show

                             when JavaScript is disabled.

                   -->

                  <div id="flashContent">

                 <p>

                          To view this page ensure that Adobe Flash Player version

                                     10.0.0 or greater is installed.

                            </p>

                            <script type="text/javascript">

                                     var pageHost = ((document.location.protocol == "https:") ? "https://" :       "http://");

                                     document.write("<a href='http://www.adobe.com/go/getflashplayer'><img src='"

                                                                           + pageHost + "www.adobe.com/images/shared/download_buttons/get_flash_player.gif' alt='Get Adobe Flash player' /></a>" );

                            </script>

        </div>

              <div id="iform">

                            <form name="form1" οnsubmit="return false;">

                                               <input type="text" name="input" size="40" value="" />

                                               <input type="button" value="發送資料到SWF" οnclick="sendToActionScript(this.form.input.value);" /><br />

                                               <textarea cols="50" rows="10" name="output" readonly="true">初始化...</textarea>

                            </form>

                   </div>

         <noscript>

            <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="650" height="314" id="ExternalInterfaceExample">

                <param name="movie" value="ExternalInterfaceExample.swf" />

                <param name="quality" value="high" />

                <param name="bgcolor" value="#ffffff" />

                <param name="allowScriptAccess" value="sameDomain" />

                <param name="allowFullScreen" value="true" />

                <!--[if !IE]>-->

                <object type="application/x-shockwave-flash" data="ExternalInterfaceExample.swf" width="100%" height="100%">

                    <param name="quality" value="high" />

                    <param name="bgcolor" value="#ffffff" />

                    <param name="allowScriptAccess" value="sameDomain" />

                    <param name="allowFullScreen" value="true" />

                <!--<![endif]-->

                <!--[if gte IE 6]>-->

                         <p>

                                   Either scripts and active content are not permitted to run or Adobe Flash Player version

                                   10.0.0 or greater is not installed.

                         </p>

                <!--<![endif]-->

                    <a href="http://www.adobe.com/go/getflashplayer" target="_blank" rel="external nofollow" >

                        <img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash Player" />

                    </a>

                <!--[if !IE]>-->

                </object>

                <!--<![endif]-->

            </object>

             </noscript>               

   </body>

</html>

//===================================================

運作後截圖

SWF(ActionScript3.0)與JavaScipt(JS)通信示例

繼續閱讀