Flex나 Flash를 하다보면 Javascript와 서로
통신할
필요가 있다. 이때 사용하는 클래스가 ExternalInterface이다. 아래코드는 ExternalInterface를 이용한 예제이다.
Flex Builder에서 html-template 폴더에 있는 내용은 컴파일시 bin폴더에 그대로 컴파일
결과물이
나온다.
가령 html-template폴더 내에 index.template.html은 bin폴더안 프로젝트명.html 으로 변환되어
나온다.
index.template.html은 Flex결과물인 swf를 출력하기 위한 기본뼈대html문서이다. mx:Application에서 설정한 높이, 폭가
index.template.html
내에 $(width), $(height), $(application)이 컴파일후 각각 100%, 100%, 프로젝트명 등으로
변경되어
bin 디렉토리에 프로젝트명.html문서가 만들어 지게 된다.
이 사실을
잘
알고 있다면 쉽게 ExternalInterface를 연습하는데 큰 무리가 없다고 본다.
ExternalInterface에
대해 더 자세히 알고 싶다면
http://flexdocs.kr 에서 ExternalInterface로 검색해보길
바란다.
예제 및 도큐먼트를 참고할 수 있을 것이다.
ExExternalInterface.mxml (Language : java)
<?xml version=
"1.0" encoding=
"utf-8" ?>
<mx:Application xmlns:mx=
"http://www.adobe.com/2006/mxml" layout=
"absolute" width=
"600" height=
"350" creationComplete=
"init()" >
<mx:Script>
<!
[ CDATA
[ public function init
( ) :
void { txtMsg.
text +=
"초기화중...\r " ;
if ( ExternalInterface.
available ) { ExternalInterface.
addCallback ( "sendToActionScript" , receivedFromJavaScript
) ;
if ( checkJavaScriptReady
( ) ) { txtMsg.
text +=
"Javascript가 준비됨\r " ;
} else { txtMsg.
text +=
"JavaScript가 준비되지 못했음 대기 \n " ;
var readyTimer:
Timer =
new Timer ( 100 ,
0 ) ;
readyTimer.
addEventListener ( TimerEvent.
TIMER , timerHandler
) ;
readyTimer.
start ( ) ;
} } else { txtMsg.
text +=
"External Interface를 사용할 수 없음\r " ;
} } private function receivedFromJavaScript
( value:
String ) :
void { txtMsg.
text +=
"JavaScript says: " + value +
"\r " ;
} private function checkJavaScriptReady
( ) :
Boolean { var isReady:
Boolean = ExternalInterface.
call ( "isReady" ) ;
return isReady;
} private function timerHandler
( event:TimerEvent
) :
void { txtMsg.
text +=
"자바스크립트 상태 Check중...\r " ;
var isReady:
Boolean = checkJavaScriptReady
( ) ;
if ( isReady
) { txtMsg.
text +=
"JavaScript가 준비됨. \r " ;
Timer ( event.
target ) .
stop ( ) ;
} } private function clickHandler
( event:
MouseEvent ) :
void { if ( ExternalInterface.
available ) { ExternalInterface.
call ( "sendToJavaScript" , txtName.
text ) ;
txtName.
text =
"" ;
} } ] ] >
</mx:Script>
<mx:Style>
Application
{ fontSize:12pt;
} </mx:Style>
<mx:TextInput x=
"10" y=
"10" id=
"txtName" width=
"189.5" />
<mx:
Button x=
"207.5" y=
"10" label=
"자바스크립트로 보내기" id=
"btnSendToJS" width=
"146" height=
"24" click=
"clickHandler(event)" />
<mx:
TextArea id=
"txtMsg" x=
"10" y=
"57" text=
"text" width=
"580" height=
"283" />
</mx:Application>
굵게 표시된 부분이 추가된겁니다. body에
onload ="pageInit()" 이 추가되었다는 것을 꼭 확인하세욤~
^^
index.template.html (Language : html4strict)
<!-- saved from url=(0014)about:internet --> <html lang ="en" > <head> <meta http-equiv ="Content-Type" content ="text/html; charset=utf-8" /> <title> ${title}
</title> <script src ="AC_OETags.js" language ="javascript" > </script> <style> body { margin: 0px; overflow:hidden }
</style> <script language ="JavaScript" type ="text/javascript" > <!-- // ----------------------------------------------------------------------------- // Globals // Major version of Flash required var requiredMajorVersion = ${version_major}; // Minor version of Flash required var requiredMinorVersion = ${version_minor}; // Minor version of Flash required var requiredRevision = ${version_revision}; // ----------------------------------------------------------------------------- // --> </script> <script language ="JavaScript" > var jsReady = false; function isReady() { return jsReady; } function pageInit() { jsReady = true; document.forms["form1"].output.value += "\n" + "JavaScript is ready. \n"; } function thisMovie(movieName) { if(navigator.appName.indexOf("Microsoft") != -1) { return window[movieName]; } else { return document[movieName]; } } function sendToActionScript(value) { thisMovie("${application}").sendToActionScript(value); document.forms["form1"].input.value = ""; } function sendToJavaScript(value) { document.forms["form1"].output.value += "ActionScript says:" + value + "\n"; }</script> </head> <body scroll="no" onload ="pageInit()" > <script language ="JavaScript" type ="text/javascript" src ="history.js" > </script> <script language ="JavaScript" type ="text/javascript" > <!-- // Version check for the Flash Player that has the ability to start Player Product Install (6.0r65) var hasProductInstall = DetectFlashVer(6, 0, 65); // Version check based upon the values defined in globals var hasRequestedVersion = DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision); // Check to see if a player with Flash Product Install is available and the version does not meet the requirements for playback if ( hasProductInstall && !hasRequestedVersion ) { // MMdoctitle is the stored document.title value used by the installation process to close the window that started the process // This is necessary in order to close browser windows that are still utilizing the older version of the player after installation has completed // DO NOT MODIFY THE FOLLOWING FOUR LINES // Location visited after installation is complete if installation is required var MMPlayerType = (isIE == true) ? "ActiveX" : "PlugIn"; var MMredirectURL = window.location; document.title = document.title.slice(0, 47) + " - Flash Player Installation"; var MMdoctitle = document.title; AC_FL_RunContent( "src", "playerProductInstall", "FlashVars", "MMredirectURL="+MMredirectURL+'&MMplayerType='+MMPlayerType+'&MMdoctitle='+MMdoctitle+"", "width", "${width}", "height", "${height}", "align", "middle", "id", "${application}", "quality", "high", "bgcolor", "${bgcolor}", "name", "${application}", "allowScriptAccess","always", "type", "application/x-shockwave-flash", "pluginspage", "http://www.adobe.com/go/getflashplayer" ); } else if (hasRequestedVersion) { // if we've detected an acceptable version // embed the Flash Content SWF when all tests are passed AC_FL_RunContent( "src", "${swf}", "width", "${width}", "height", "${height}", "align", "middle", "id", "${application}", "quality", "high", "bgcolor", "${bgcolor}", "name", "${application}", "flashvars",'historyUrl=history.htm%3F&lconid=' + lc_id + '', "allowScriptAccess","always", "type", "application/x-shockwave-flash", "pluginspage", "http://www.adobe.com/go/getflashplayer" ); } else { // flash is too old or we can't detect the plugin var alternateContent = 'Alternate HTML content should be placed here. ' + 'This content requires the Adobe Flash Player. ' + '<a href=http://www.adobe.com/go/getflash/> Get Flash
</a> ';
document.write(alternateContent); // insert non-flash content
}
// -->
</script> <noscript> <object classid ="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id ="${application}" width ="${width}" height ="${height}" codebase ="http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab" > <param name ="movie" value ="${swf}.swf" /> <param name ="quality" value ="high" /> <param name ="bgcolor" value ="${bgcolor}" /> <!--<param name="allowScriptAccess" value="sameDomain" /> -->
<param name ="allowScriptAccess" value ="always" /> <embed src ="${swf}.swf" quality="high" bgcolor ="${bgcolor}" width ="${width}" height ="${height}" name ="${application}" align ="middle" play="true" loop="false" quality="high" allowScriptAccess="sameDomain" type ="application/x-shockwave-flash" pluginspage="http://www.adobe.com/go/getflashplayer" > < /embed> </object> </noscript> <iframe name ="_history" src ="history.htm" frameborder ="0" scrolling ="no" width ="22" height ="0" > </iframe> <form name ="form1" onsubmit ="return false;" > <input type ="text" name ="input" value ="" /> <input type ="button" value ="Send" onclick ="sendToActionScript(this.form.input.value);" /> <br /> <textarea cols ="60" rows ="20" name ="output" readonly ="true" > Initializing...</textarea> </form> </body> </html> 글쓴이 : 지돌스타(
http://blog.jidolstar.com/214 )