JS和AIR(FLEX)的互相调用详解
前言:最近要在AIR项目中添加使用QQ和Sina登录 但是腾讯和新浪没有提供相关的SDK 所以就只能使用他们的js-SDK来登录 所以这里就涉及到js和AIR的交付问题
开始在百度找好久都没解决问题 发现国内同行都喜欢贴同样的代码 而且还没有经过测试的代码 好了 不吐槽了 上代码
Flex代码
<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml"
layout="absolute" creationComplete="init()">
<mx:Script>
<![CDATA[
private var calledFromJSHandlerFunction:Function = calledFromJSHandler;
private function init():void{
html.addEventListener(Event.HTML_DOM_INITIALIZE, domInitialized);//添加Event.HTML_DOM_INITIALIZE类型事件 此处Event.HTML_DOM_INITIALIZE可能会报未定义常量 那么请使用 flash.events.Event.HTML_DOM_INITIALIZE
html.location = "htmlwithJS.html";
}
private function domInitialized(event:Event):void{
html.htmlLoader.window.calledFromJSHandlerFunction = calledFromJSHandlerFunction;//在js中注册calledFromJSHandlerFunction函数 当js调用calledFromJSHandlerFunction时 就会触发flex 的calledFromJSHandlerFunction方法
}
private function calledFromJSHandler():void {
mx.controls.Alert.show("ActionScript called from JavaScript", "Alert");
}
private function doHTMLAlert( ):void {
html.htmlLoader.window.calledFromAS();//Flex调用js方法
}
]]>
</mx:Script>
<mx:Button id="alertBtn" label="Call JavaScript from ActionScript"
click="doHTMLAlert()" x="137" y="10"/>
<mx:HTML id="html" x="137" y="40" width="339"/>
<mx:Label x="10" y="12" text="Normal MXML Button"/>
<mx:Label x="28" y="38" text="HTML component"/>
</mx:WindowedApplication>
html代码
<html>
<script language="Javascript">
function calledFromAS() {//js方法
alert('Hello from ActionScript');
}
</script>
<body>
<input type="button"
value="Call ActionScript from JavaScript"
onclick="calledFromJSHandlerFunction()" />//调用flex方法
<br />
<input type="button"
value="Normal JavaScriptAlert"
onclick="alert('Hello from JavaScript')">
</body>
</html>
注:js调用flex 在flex代码注册js函数一定要写在html控件的Event.HTML_DOM_INITIALIZE类型事件里 这样当js调用时才能触发flex对应的方法
出处:http://blog.everythingflex.com/2008/02/25/air-actionscript-javascript-bridge/