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 )
크리에이티브 커먼즈 라이선스
Adobe Flash Platform
ExternalInterface ,
flex ,
javascript
var realTimeMonitor:String = "http:localhost:8080/corona_service/corona_remote-debug/realTimeMonitor.swf;
ExternalInterface.call("window.open", realTimeMonitor, '_blank','menubar=yes,resizable=yes'); 으로 외부창을 만들었는데요 닫을 경우에는 window.onbeforunload 이벤트가 호출이 되지 않습니다. 중복해서 창이 뜨지 않게 만들려고 브라우저 x버튼 클릭 시 이벤트 처리를 주고 싶은데 방법을 혹시 아시는지요?..
그것은 flash문제가 아니라 javascript 문제인듯하네요. 창이 닫혀질때의 이벤트이니깐요. 명확히 무엇을 하려는 의도이신지요?
메인(main.swf)창이 있으면 버튼을 클릭해서 외부창(real.swf)을 띄워주었는데 중복해서 창이 뜨는걸 막아야 하는데 띄워놓은 외부창을 닫아야 또 그 화면을 띄우게 해줘야 합니다. 이미 띄워놓은 외부창을 닫을 때 생기는 이벤트 처리 부분을 어떻게 해야될지 모르겠습니다. window.onbeforunload 이벤트로 안 먹힙니다. main.swf 창을 닫을 때는 자바스크립트에서 window.onbeforunload 이벤트가 먹히는데 왜 다른지 이유를 모르겠습니다.
flash문제가 아니라 javascript 문제 아닌가요? 이벤트가 안먹힌다는 문제는 javascript 관련 문서를 참고하셔서 해결하심이 옳을듯합니다.
잘 봤습니다.
flex에서 ExternalInterface를 통해서 index.templete.html에 접근을 하는데 다른 html에 접근을 하는 방법이 있습니까? index.templete.html에서 다른 html에 접근 한다던지 하는 방법은 있을 것 같은데 궁금하네요.
ExternalInterface는 SWF자신이 속한 페이지에 정의된 자바스크립트 함수를 호출하는 역할을 합니다. 다른 HTML에 접근한다는 것은 ExternalInterface의 적용범위에서 벗어납니다.