AS与JS互相通信

不说废话,直接贴代码。。。

AsJsComm.as

package {
	import flash.display.Sprite;
	import flash.external.ExternalInterface;

	public class AsJsComm extends Sprite {
		/**
		 * 构造函数
		 */
		public function AsJsComm() {
			// 注册一个AS方法供JS调用
			ExternalInterface.addCallback('callback', callback);

			// AS调JS方法(此alert为window对象的alert方法)
			ExternalInterface.call('alert', 'AS: Hello JS!');
		}

		/**
		 * 回调方法
		 */
		public function callback(str:String):void {
			// 为了方便查看,直接调用JS的弹框
			ExternalInterface.call('alert', str);
		}
	}
}


index.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>AsJsComm</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js"></script>
</head>
<body>
<div id="flash">
  <div id="flashObj">loading...</div>
</div>
<script type="text/javascript">
(function() {
	var id = 'flashObj',
	width = '800',
	height = '680',
	version = '9.0.0',
	expressInstallSwfUrl = '',
	flashVars = {},
	params = {
		id: id,
		allowScriptAccess: 'always',
		allowFullScreen: 'true',
		quality: 'high',
		wmode: 'opaque',
		bgcolor: '#000',
		menu: 'false'
	},
	attributes = {},
	callbackFn = function(data) {},
	swfUrl = 'AsJsComm.swf';
	swfobject.embedSWF(swfUrl, id, width, height, version, expressInstallSwfUrl, flashVars, params, attributes, callbackFn);
	window.onload = function() {
		// JS调AS方法
		document.getElementById(id).callback('JS: Nice to meet you AS!');
	};
})();
</script>
</body>
</html>

简要说明:

1、只要html页面中能正常访问的JS方法,AS中都可以直接用ExternalInterface.call调用,不需要另作其他声明;

2、AS中的方法要供JS调用,必须先调用ExternalInterface.addCallback注册,注册的方法会绑定在html页中flash元素的object对象上;

3、通信的时候,应保证调用方法所属的资源加载完毕,如:这里的JS调AS中的方法,就要求flash已正确加载完毕才行;

4、没了。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值