转载请注明来自:http://blog.csdn.net/skyman_2001
Flash外部通信有三种:getURL、fscommand和externalInterface,这里只讲fscommand和externalInterface的使用。Flash早期只有fscommand,externalInterface是后来出现的,externalInterface在传递参数方面比fscommand更强大,fscommand只能传递一个字符串,而externalInterface可以传递多个参数,而且可以是各种类型,甚至是数组。
下面代码演示了如何通过fscommand和externalInterface让Flash和js通信:
AS代码:
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.text.TextField;
import flash.system.fscommand;
import flash.external.ExternalInterface;
/**
* ...
* @author skyman
*/
public class Main extends Sprite
{
private var txt:TextField;
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
trace("----Init--------");
removeEventListener(Event.ADDED_TO_STAGE, init);
txt = new TextField();
txt.width = 500;
txt.text = "Click Me!";
addChild(txt);
txt.addEventListener(MouseEvent.CLICK, onClick);
ExternalInterface.addCallback("showMsg2", showMsg);
}
private function onClick(event:MouseEvent):void
{
fscommand("call_alert", "fscommand test");
ExternalInterface.call("showMsg", [0,1,"two",{a:1,b:2}]);
}
public function showMsg(msg:Array):void
{
if(msg[3].b != 2)
txt.text = msg[2] +"," + msg[3].a;
else
txt.text = "msg[3].b == 2";
}
}
}
JS代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>proj1</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<SCRIPT LANGUAGE="VBScript">
Sub proj1_FSCommand(ByVal command, ByVal args)
call proj1_DoFSCommand(command, args)
End Sub
</SCRIPT>
<script type="text/javascript">
function getID( swfID )
{
if(navigator.appName.indexOf("Microsoft") != -1)
{
return window[swfID];
}
else
{
return document[swfID];
}
}
function proj1_DoFSCommand(command, args){
if(command == "call_alert")
alert(args);//读取参数信息
}
function showMsg(msg)
{
alert(msg[3].a+","+msg[3].b);
getID("proj1").showMsg2(msg);
}
</script>
</head>
<body>
<div id="altContent">
<OBJECT
CLASSID="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
WIDTH="100%"
HEIGHT="100%"
CODEBASE="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab"
ID=proj1>
<PARAM NAME="MOVIE" VALUE="proj1.swf">
<PARAM NAME="PLAY" VALUE="false">
<PARAM NAME="LOOP" VALUE="false">
<PARAM NAME="QUALITY" VALUE="high">
<PARAM NAME="SCALE" VALUE="SHOWALL">
<EMBED
NAME="testmovie"
SRC="proj1.swf"
WIDTH="100%"
HEIGHT="100%"
PLAY="false"
LOOP="false"
QUALITY="high"
SCALE="SHOWALL"
swLiveConnect="true"
PLUGINSPAGE="http://www.macromedia.com/go/flashplayer">
</EMBED>
</OBJECT>
</div>
</body>
</html>