这也是js方法"eval"的一种应用。
在flash中生成js的方法,然后通过ExternalInterface调用。
通过这种机制,可以在Flash中实现整个页面刷新,以及在Flash中获取所在网页的链接等功能。
代码很简单,我就不直接说了,贴出来,大家可以直接看效果
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" fontFamily="Times New Roman"
fontSize="12" creationComplete="init()">
<mx:Script>
<![CDATA[
import mx.controls.Alert;
import flash.external.ExternalInterface;
private function init():void
{
//需要在js生成的代码
var str:String = "function testMethod(str)";
str = str + "{";
str = str + "alert('Flash传来:' + str);";
str = str + "return 'js返回:' + str;";
str = str + "}";
//利用eval函数生成
ExternalInterface.call("eval", str);
}
private function buttonClick():void
{
//调用刚刚生成的方法
var str:String = ExternalInterface.call("testMethod", valueText.text);
Alert.show(str);
}
private function fulshHtmlEvent():void
{
//刷新页面
ExternalInterface.call("eval", "location.reload();");
}
]]>
</mx:Script>
<mx:Button label="提交" id="subimtBtn" click="buttonClick()"/>
<mx:TextInput width="122" id="valueText"/>
<mx:Label text="Flash数据:"/>
<mx:Button label="刷新页面" id="flushBtn" click="fulshHtmlEvent()"/>
</mx:Application>
总结:
实现Flash调用JS方法,有以下三点需要注意:
必须在Flash代码中导入ExternalInterface,即添加如下代码
import flash.external.ExternalInterface
引用Flash的object标签必须有id属性。
object标签中必须传递allowScriptAccess参数,同时object中的embed标签也要加上这个属性。
allowScriptAccess的值可以为always, sameDomain, never。