---
title: "AS与JS相互通信(Flex中调用js函数)"
author: "speed847"
date: "2009-11-15T23:01:13Z"
tags: []
slug: "as-js-flex-js"
draft: false
lastmod: "2009-11-15T23:17:49Z"
id: 517787
url: "https://speed847.iteye.com/blog/517787"
---

目前，有些基于html的网页 内嵌了swf。html与swf之间的通信是很有必要的。从下面的文章中可以学到如何在flex代码中调用html页面的javascript函数。

附：html内嵌swf的代码

&lt;object width="550" height="300"&gt;  
&lt;param name="movie" value="PTJ\_Portal\_Demo1.swf"&gt;  
&lt;embed src="PTJ\_Portal\_Demo1.swf" width="800" height="300"&gt;  
&lt;/embed&gt;  
&lt;/object&gt;

 

http://www.blogjava.net/Alpha/archive/2009/06/27/284373.html

 

Flex中As调用Js的方法是：  
     1、导入包 （import flash.external.ExternalInterface;）  
     2、使用ExternalInterface.call("Js函数名称",参数)进行调用，其返回的值就是Js函数所返回的值  
   
Js调用As的方法是：  
     1、导入包 （import flash.external.ExternalInterface;）  
     2、在initApp中使用ExternalInterface.addCallback("用于Js调用的函数名",As中的函数名)进行注册下  
     3、js中 就可以用document.getElementById("Flas在Html中的ID").注册时设置的函数名（参数）进行调用

# **as和js通信addcallback失效**

参考原文：http://www.zhaohongri.cn/?p=14

情况一：flash一旦在浏览器里cache住，如果在as里一开始就addcallback就会失效  
情况二：一个js函数上来就调用as的一个函数的时候，页面会报错，提示找不到这个flash对象，或者函数没有定义。Flash8的时代，针对 ExternalInterface这个类，文档里只说明了怎么用，而没有具体说怎么合理的组织和页面的结构，一直到了cs3的时代，帮助里才说明了正确 的函数注册和js调用的过程，具体的见Flash cs3帮助。大概的代码如下：

js部分：

           &lt;script&gt;  
var jsReady=false;  
var swfReady=false;

function isReady(){  
return jsReady;  
}

function setSwfIsReady(){  
      swfReady=true;  
   getSWF(”flashobj”).fun()

}

function pageInit(){  
     jsReady=true;  
}

function getSWF(movieName) {  
   if (navigator.appName.indexOf(”Microsoft”) != -1) {  
    return window\[movieName+”\_ob”];  
   } else {  
    return document\[movieName+”\_em”];  
   }  
}

onload=function(){  
   pageInit();  
}

&lt;/script&gt;

注意，在getSWF函数里用了 return window\[movieName+”\_ob”]和return document\[movieName+”\_em”]，在IE下，如果object标签和embed表现用同样的id，通过js去访问flash对象的时 候，IE会认不出，FF是没有问题的

as部分

private function registerJsFun():void{  
       if(ExternalInterface.available){  
     try{  
      var containerReady:Boolean=isContainerReady();  
      //ExternalInterface.call(”ceshi”,”registerJsFun:”+containerReady);  
      if(containerReady){  
       //注册函数  
       setupCallBacks();  
      }else{  
       //检测是否准备好  
       var readyTimer:Timer=new Timer(100);  
       readyTimer.addEventListener(TimerEvent.TIMER,timeHandler);  
       readyTimer.start();  
      }  
     }catch(error:Error){  
      trace(error)  
     }  
    }else{  
     trace(”External interface is not available for this container.”);  
    }  
   }  
    
private function timeHandler(event:TimerEvent):void{  
var isReady:Boolean=isContainerReady();  
      if(isReady){  
   Timer(event.target).stop();  
   setupCallBacks();  
}  
}

private function isContainerReady():Boolean{  
var result:Boolean=Boolean(ExternalInterface.call(”isReady”));  
return result;  
}

private function setupCallBacks():void{  
       ExternalInterface.addCallback(”fun”,fun);

        ExternalInterface.call(”setSwfIsReady”);  
     }

具体我就不解释了，不明白的可以仔细去看下cs3帮助，大概的意思就是页面开始渲染的时候js去调用swf对象，有可能swf对象没有完全 load完，所以这个触发器要从flash开始，当flash加载的时候就开始不停的调用页面的一个函数，取一个页面是否加载完毕的标识，当 pageonLoad后，这个标识为true了，说明flash也加载完毕了，这个时候flash再开始注册函数，同时调用页面的js，让js调用 Flash对象

 

实例：a.mxml

&lt;!-- &lt;br /&gt; &lt;br /&gt; Code highlighting produced by Actipro CodeHighlighter (freeware)&lt;br /&gt; http://www.CodeHighlighter.com/&lt;br /&gt; &lt;br /&gt; --&gt;&lt;? xml version="1.0" encoding="utf-8" ?&gt;  
&lt; mx:Application  xmlns:mx ="http://www.adobe.com/2006/mxml"  layout ="absolute" &gt;  
     &lt; mx:Script &gt;  
         &lt;![CDATA[     
      import flash.external.\*;  
      public function asFunc():String {  
          return sending\_ti.text;  
      }  
        
      public function initApp():void {  
        //AddCallback方法允许javascript调用flash时间上函数   
          ExternalInterface.addCallback("flexFunctionAlias", asFunc);  
      }  
        
         public function callWrapper():void {        
             var f:String = "changeDocumentTitle";  
       //ExternalInterface.call(functionName:String,Parameters)可以调用javascript函数  
       //参数1: functionName – 你想要调用的javascript函数名要以字符串的形式  
       //参数2: Parameters – 需要传递给javascript函数的参数，用逗号分开，是可选的。                
             var getJSValue:String = ExternalInterface.call(f,"New Title");  
             received\_ti.text = getJSValue;  
        }

         ]]&gt;  
     &lt;/ mx:Script &gt;  
     &lt; mx:Button  id ="send\_button"  x ="368"  y ="100"  click ="initApp();"  label ="发送"  fontSize ="12"  width ="62" /&gt;  
     &lt; mx:TextInput  id ="received\_ti"  x ="148"  y ="62"  width ="203"  fontSize ="12" /&gt;  
     &lt; mx:TextInput  id ="sending\_ti"  x ="148"  y ="100"  width ="203"  fontSize ="12" /&gt;  
     &lt; mx:Label  x ="105"  y ="65"  text ="收到"  fontSize ="12" /&gt;  
     &lt; mx:Label  x ="105"  y ="103"  text ="发送"  fontSize ="12" /&gt;  
     &lt; mx:Button  x ="368"  y ="64"  click ="callWrapper();"  label ="接收"  fontSize ="12"  width ="62" /&gt;  
&lt;/ mx:Application &gt;

index.html

&lt;!-- &lt;br /&gt; &lt;br /&gt; Code highlighting produced by Actipro CodeHighlighter (freeware)&lt;br /&gt; http://www.CodeHighlighter.com/&lt;br /&gt; &lt;br /&gt; --&gt;&lt;! DOCTYPE HTML PUBLIC "-//W3C//Dtd nowrap HTML 4.01 Transitional//EN" &gt;  
&lt; html &gt;  
&lt; head &gt;  
   &lt; base  target ="\_self" &gt;  
   &lt; title &gt;&lt;/ title &gt;  
   &lt; meta  http-equiv ="Content-Type"  content ="text/html; charset=utf-8"   /&gt;  
   &lt; meta  http-equiv ="pragma"  content ="no-cache" &gt;  
   &lt; meta  http-equiv ="cache-control"  content ="no-cache" &gt;  
   &lt; meta  http-equiv ="expires"  content ="0" &gt;  
&lt;/ head &gt;

&lt; script  language ="JavaScript" &gt;    
     function  callApp() {  
         var  x  =  MyFlexApp.flexFunctionAlias();  
        document.getElementById('receivedField').value  =  x;  
    }

     function  changeDocumentTitle(a) {  
        window.document.title = a;  
         return  document.getElementById('sendField').value;  
    }  
&lt;/ script &gt;

&lt; body  style ='overflow-x:hidden;overflow-y:hidden' &gt;  
   &lt; form  name ="htmlForm" &gt;  
     数据发送给AS:  
     &lt; input  type ="text"  id ="sendField"   /&gt;  
     &lt; input  type ="button"  value ="发送"  onclick =""   /&gt;&lt; br  /&gt;  
     &lt; br  /&gt;  
    接收AS的数据:  
     &lt; input  type ="text"  id ="receivedField" &gt;  
     &lt; input  type ="button"  value ="接收"  onclick ="callApp();"   /&gt;&lt; br  /&gt;       
   &lt;/ form &gt;  
    &lt; OBJECT  id ="MyFlexApp"  classid ="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase ="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0"  WIDTH ="100%"  HEIGHT ="500" &gt;  
       &lt; PARAM  NAME =movie  VALUE ="joinJS.swf" &gt;  
       &lt; PARAM  NAME =quality  VALUE =high &gt;  
       &lt; PARAM  NAME =scale  VALUE =noborder &gt;  
       &lt; PARAM  NAME =bgcolor  VALUE =#000000 &gt;  
       &lt; EMBED  src ="joinJS.swf"  quality =high  WIDTH ="100%"  HEIGHT ="500"  scale =noborder  bgcolor =#000000  NAME ="TH2" TYPE ="application/x-shockwave-flash"  PLUGINSPAGE ="http://www.macromedia.com/go/getflashplayer" &gt;&lt;/ EMBED &gt;  
    &lt;/ OBJECT &gt;  
&lt;/ body &gt;