加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 18:29:06 所属栏目:百科 来源:网络整理
导读:今天花了一些时间整理出来了Swf 文件与JavaScript通信的示例,在此贴出供大家参考。 在ActionScript3.0与JavaScipt通信的时候需要用到ExternalInterface类。 “ ExternalInterface ”类是外部 API ,在 ActionScript 和 FlashPlayer 的容器之间实现直接通讯

今天花了一些时间整理出来了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,140,20,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,1);

?????????? this.graphics.moveTo(8,40);

?????????? this.graphics.lineTo(428,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,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>

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

运行后截图

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读