1. 程式人生 > >SWF(ActionScript3.0)與JavaScipt(JS)通訊示例

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

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

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

ExternalInterface”類是外部API,在ActionScriptFlashPlayer的容器之間實現直接通訊的應用程式程式設計介面,例如,含有JavaScriptHTML頁。推薦對所有JavaScriptActionScript之間的通訊使用ExternalInterface

HTML頁中使用JavaScript,可以呼叫FlashPlayer中的ActionScript

函式。ActionScript函式可以返回一個值,JavaScript會立即接收它作為該呼叫的返回值。

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

ExternalInterface

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

[static][read-only]指示此播放器是否位於提供外部介面的容器中。

注意:將ExternalAPIHTML一起使用時,應始終在嘗試呼叫任何JavaScript方法之前先檢查HTML是否已完全載入。

兩個重要方法

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

[static]ActionScript方法註冊為可從容器呼叫。

SecurityError&mdash包含環境屬於呼叫程式碼無權訪問的安全沙箱。修正此問題:

在包含HTML頁中的SWF檔案的<object>標籤中,設定以下引數:

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

SWF檔案中,新增以下ActionScript

flash.system.Security.allowDomain(sourceDomain)

2call(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不可用。");

}

}

/**

 * JavaScript開放的名為sendToActionScript的方法。

 * JavaScript中這樣呼叫:.sendToActionScript(instring),

 * instring就傳給本方法的value了。

 */

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

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

}

/**

 * 呼叫JavaScript暴露的方法 isReady

 */

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();

}

}

/**

 * 滑鼠點擊發送時,呼叫JavaScript暴露的方法 sendToJavaScript

 */

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" lang="en" xml:lang="en">        

    <!--

    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" />

        <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 onload="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" onsubmit="return false;">

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

                                               <input type="button" value="傳送資料到SWF" onclick="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">

                        <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>

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

執行後截圖