日期:2014-05-16  浏览次数:20473 次

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、没了。。。