as3与js通信详解

7 篇文章 0 订阅

在说AS3与js通信不得不说在网页中加入flash文件的方法。在网页中嵌入flash文件有多种方式,下面简要的讲一下:

一、传统方式:

body>
<object id="flash1" data="test.swf" height="200"type="application/x-shockwave-flash"width="200">
<param name="movie"value="test.swf">
<param name="allowScriptAccess"value="always">
</object>

</body>

二、使用开源方法swfobject.js:

这个方法简单快捷,

<head>

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

</head>

<body>
<divid="mainbox"></div>

<scripttype="text/javascript">  
    swfobject.embedSWF("test.swf", "mainbox", "200", "120", "9.0.0","expressInstall.swf");

</script>

</body>

关于swfobject.js在网上可以搜一下。还是很多的,这里推荐大家一个: 天地会


下面就来说一下重点要说的东西ExternalInterface。

ExternalInterface是一个AS3的类文件。

首先在AS3的API上面可以粗略的看一下,ExternalInterface类中主要是包括两个方法call和addCallback。

call方法:
    调用由 Flash Player 容器公开的函数,不传递参数或传递多个参数。如果该函数不可用,调用将返回 null;否则,它返回由该函数提供的值。不允许在 Opera 或 Netscape 浏览器中使用递归;在这些浏览器上,递归调用将生成 null 响应。(Internet Explorer 和 Firefox 浏览器上支持递归。)

如果该容器是 HTML 页,则此方法在 script 元素中调用 JavaScript 函数。API上面说的有点让人模糊,看下面的。

call---ActionScript调用JavaScript的方法

  1.1不带参数的情况

  JavaScript:function Show() {  alert("I am a func!");}

  ActionScript://直接用一条语句调用ExternalInterface.call("Show");

  1.2带参数的情况

   JavaScript:function Show(message) {  alert(message);}
   ActionScript:ExternalInterface.call("Show","I am a message fromAS");

   另外也可以用getURL方法调用   

   getURL("javascript:show('i am a message fromas)","_self");

addCallback方法:

将 ActionScript 方法注册为可从容器调用。成功调用 addCallBack() 后,容器中的 JavaScript 或 ActiveX 代码可以调用在 Flash Player 中注册的函数。

addCallback---JavaScript调用ActionScript的方法

   ExternalInterface.addCallback( functionName:String,closure:Function):void 

  functionName:要注册的函数名

  closure:对应的执行函数

      JS:

        function thisMovie(movieName){  
          if(navigator.appName.indexOf("Microsoft") != -1){
           return window[movieName]; 
          }else{
           return document[movieName];  
          }
        }
  
         function callAS1(){
          thisMovie("flash1").show("I am come from js program!");
        }

接下来看一个API文档中的例子:

AS3代码:

package {
    import flash.display.Sprite;
    import flash.events.*;
    import flash.external.ExternalInterface;
    import flash.text.TextField;
    import flash.utils.Timer;
    import flash.text.TextFieldType;
    import flash.text.TextFieldAutoSize;
	import flash.system.Security;

    public class Main extends Sprite {
        private var input:TextField;
        private var output:TextField;
        private var sendBtn:Sprite;

        public function Main() {
			Security.allowDomain("*");
            input = new TextField();
            input.type = TextFieldType.INPUT;
            input.background = true;
            input.border = true;
            input.width = 350;
            input.height = 18;
            addChild(input);

            sendBtn = new Sprite();
            sendBtn.mouseEnabled = true;
            sendBtn.x = input.width + 10;
            sendBtn.graphics.beginFill(0xCCCCCC);
            sendBtn.graphics.drawRoundRect(0, 0, 80, 18, 10, 10);
            sendBtn.graphics.endFill();
            sendBtn.addEventListener(MouseEvent.CLICK, clickHandler);
            addChild(sendBtn);

            output = new TextField();
            output.y = 25;
            output.width = 450;
            output.height = 325;
            output.multiline = true;
            output.wordWrap = true;
            output.border = true;
            output.text = "Initializing...\n";
            addChild(output);

            if (ExternalInterface.available) {
                try {
                    output.appendText("Adding callback...\n");
                    ExternalInterface.addCallback("sendToActionScript", receivedFromJavaScript);
                    if (checkJavaScriptReady()) {
                        output.appendText("JavaScript is ready.\n");
                    } else {
                        output.appendText("JavaScript is not ready, creating timer.\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 is not available for this container.");
            }
        }
        private function receivedFromJavaScript(value:String):void {
            output.appendText("JavaScript says: " + value + "\n");
        }
        private function checkJavaScriptReady():Boolean {
            var isReady:Boolean = ExternalInterface.call("isReady");
            return isReady;
        }
        private function timerHandler(event:TimerEvent):void {
            output.appendText("Checking JavaScript status...\n");
            var isReady:Boolean = checkJavaScriptReady();
            if (isReady) {
                output.appendText("JavaScript is ready.\n");
                Timer(event.target).stop();
            }
        }
        private function clickHandler(event:MouseEvent):void {
            if (ExternalInterface.available) {
                ExternalInterface.call("sendToJavaScript", input.text);
            }
        }
    }
}

html的代码:

 <!-- saved from url=(0014)about:internet -->
 <html lang="en">
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title>asjs</title>
 <script language="JavaScript">
     var jsReady = false;
     function isReady() {
         return jsReady;
     }
     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];
         }
     }
     function sendToActionScript(value) {
         thisMovie("asjs").sendToActionScript(value);
     }
     function sendToJavaScript(value) {
         document.forms["form1"].output.value += "ActionScript says: " + value + "\n";
     }
 </script>
 </head>
 <body οnlοad="pageInit();">
 
     <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
             id="asjs" width="500" height="375"
             codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab">
         <param name="movie" value="asjs.swf" />
         <param name="quality" value="high" />
         <param name="bgcolor" value="#869ca7" />
         <param name="allowScriptAccess" value="always" />
         <embed src="asjs.swf" quality="high" bgcolor="#869ca7"
             width="500" height="375" name="asjs" align="middle"
             play="true" loop="false" quality="high" allowScriptAccess="always"
             type="application/x-shockwave-flash"
             pluginspage="http://www.macromedia.com/go/getflashplayer">
         </embed>
     </object>
 
     <form name="form1" οnsubmit="return false;">
         <input type="text" name="input" value="" />
         <input type="button" value="Send" οnclick="sendToActionScript(this.form.input.value);" /><br />
         <textarea cols="60" rows="20" name="output" readonly="true">Initializing...</textarea>
     </form>
 
 </body>
 </html>

可以看到,页面中AS与js互相传值。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值