상세 컨텐츠

본문 제목

[AS] 플래시 as3.0 브라우져 액션스크립트 연동 관련 (자바스크립트 연동, asp, jsp, php 연동)

ADOBE/ ActionScript

by AlrepondTech 2020. 9. 21. 01:33

본문

반응형

 

 

 

 

=================================

=================================

=================================

 

 

 

 

 

 

 

출처: http://cafe.naver.com/flashdev.cafe?iframe_url=/ArticleRead.nhn%3Farticleid=8093

안녕하세요

밥먹구 왔습니다 -0-;;

파란토끼님의 기대에 부응하기 위해

addCallback 사용법에 대해서 강좌 들어갑니다.

.call 이 플래시가 자바스크립트를 가지고 노는거라면

.addCallback 은 자바가 플래시를 가지고 노는거라고 보시면 됩니다.

플래시 내부의 함수를 바깥에서 접속할수 있도록 registry(F1 Help 는 register 라는 단어를 사용했습니다. 아마도 메모리에 저장시키기 때문이겠죠?) 시켜서 자바스크립트가 직접 컨트롤 할 수 있도록 해놓는것입니다.

간단한 기본 문구 부터 살펴보고 가죠.

ExternalInterface.addCallback("자바가 쓸 함수명", 인스턴스, 메소드명);

입니다.

예를 들어

 

ExternalInterface.addCallback("EI_fnc", "", swf_fnc);

라는 문장은 swf_fnc 라고 선언된 플래시내의 함수를

자바스크립트가 EI_fnc 라는 함수명으로 컨트롤 할 수 있다는 것이지요.

자 예제는 이렇습니다.

플래시내에서 moveMC(xy, num) 이라는 함수가 있습니다.

방향과 움직일 거리를 입력받아 무비클립을 이동시키는 함수입니다.

이 함수를 바깥으로 열어놓아서 자바스크립트가 onClick="moveMC(x, 10)" 이라는 형태로 직접 조정할 수 있도록 하는것입니다.

// 플래시 파트

import flash.external.ExternalInterface;
var successEI = ExternalInterface.addCallback("moveMC", "", moveMC);

if(!successEI){getURL("javascript:alert('Fail');"); }
goX = mc._x;
goY = mc._y;
function moveMC(xy, num){
 if(xy == "x"){
  goX += num;
 }else{
  goY += num;
 }
}
mc.onEnterFrame = function(){
 this._x += 0.3*(_root.goX - this._x);
 this._y += 0.3*(_root.goY - this._y);
}

// Javascript 파트

<script language="javascript">
function mc_move(send_xy, send_num){
 thisMovie("EI_flash").moveMC(send_xy, send_num);
}
function thisMovie(movieName) {
    if (navigator.appName.indexOf("Microsoft") != -1) {
        return window[movieName]
    }
    else {
        return document[movieName]
    }
}
</script>

 

// Embed 파트

id="EI_flash">
  <param name="movie" value="externalinterface.addCallback.swf" />
  <param name="quality" value="high" />
  <param name="allowScriptAccess" value="always" />
   allowScriptAccess="always" showLiveConnect="true" name="EI_flash"></embed>
</object>

 

자 하나씩 뜯어먹어보까요~

 

1. 플래시 파트

굳이 깊이 설명안드리겠습니다.

import 부분이 이해안가시는 분들은 제가 아래 써놓은 call 오픈강좌를 참고해주셔요 [ http://cafe.naver.com/flashdev/8089 ]

ExternalInterface.addCallback(methodName, "", method) 형태로 선언해놓았습니다.

successEI 는 함수가 제대로 addCallback 된것인지 확인해주는 예외처리구문입니다.

 

2. Javascript 파트

thisMovie("EI_flash").moveMC(send_xy, send_num);

이부분이 플래시를 컨트롤 해주는 부분입니다.

EI_flash 는 플래시 embed 부분과 object부분에 설정해놓은 플래시네임입니다.

moveMC 는 ExternalInterface.addCallback(methodName, "", method) 이부분에서 methodName 을 가리킵니다.

methodName 이 자바스크립트에서 컨트롤 하는 함수명이라고 설명드렸습니다.

 

3. Embed 파트

.call 사용법과 마찬가지로

<object ... id="EI_flash">

<embed ... allowScriptAccess="always" showLiveConnect="true" name="EI_flash">

<param name="allowScriptAccess" value="always" />

를 추가해줍니다.

 

실제 액션은 onClick="mc_move('x', 20)" 과 같이 자바스크립트함수를 가지고 컨트롤 하면 됩니다.

의외로 사용법이 쉽습니다.

처음에 알아내기에는 좀 시행착오가 많았지만

알아내고 나니 정말 사용법이 간단하군요.

fscommand 로 변수쪼개서 받던 시대는 이제 간듯 싶습니다^^

다들 홧팅!!

 

p.s) 사실 html 에 VB+ 코드가 들어간다는게 여간 찜찜한게 아니었습니다...

p.s2) 혹시 저랑 MFD 같이 공부하실분 ㅎㅎ 예전에 65점 맞고 낙방했습죠 -0-

 

 

 

=================================

=================================

=================================

 

 

 

출처: http://cafe.naver.com/flashdev.cafe?iframe_url=/ArticleRead.nhn%3Farticleid=8089&

예전에 getURL 로 폼값바꾸던 시대는 이제 완전 빠빠이 인것 같습니다.

MX에서인가 fscommand 라는 기능이 생겨서 고수유저들이 많이 사용했지만

저같이 디자이너 출신의 잡부팀장(-_-;;) 에게는 사용하기 수월치 않더군요.

레퍼런스도 많이 공개되지 않아있어서 더 그랬던것 같습니다.

하지만 플래시 8 에서 ExternalInterface 라는 함수가 지원되면서

자바스크립트랑 플래시는 연인사이로 한걸음 다가서게 되었습니다.

 

자 바로 본론으로 들어갑시다.

사용법은 fscommand 방식과 비슷합니다.

//Flash 파트

System.useCodepage = true;

import flash.external.ExternalInterface;

btn.onPress = function(){

 var getTXT = ExternalInterface.call("Hello", _root.txt);

 _root.txt = getTXT;

}

 

//Html 파트

<script language="javascript">

function Hello(msg){

 msg = "Hi~!! "+msg+" \n만나서 반갑습니다.";

 return msg;

}

</script>

 

//Embed 파트

<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0" width="192" height="192"id="external_flash">
  <param name="movie" value="externalinterface.swf">
  <param name=quality value=high>
  <param name="allowScriptAccess" value="always">
  <embed src="externalinterface.swf" quality=high pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash" width="192" height="192" allowScriptAccess="always" swLiveConnect=true name="external_flash"></embed>
</object>

 

자 그럼 하나씩 살펴보도록 합시다.

 

1. 플래시 파트

간단합니다.

그만큼 사용하기 편하다는 것이겠죠.

import flash.external.ExternalInterface;

ExternalInterface 클래스를 불러오는것이죠.

Flash 8 에서 지원되는 여러가지 기능들은 대체로 Import 하여 사용하게 됩니다. 필터, 지오메트릭, 함수 등등...

ExternalInterface.call("Hello", _root.txt);

실제적으로 자바함수와 꼼지락 대는 부분입니다.

자신이 속해있는 파일에서 Hellow 라는 함수를 _root.txt 라는 변수를 대입하여 그 결과값을 받는다는 말입니다.

ExternalInterface.call(함수명, 변수) 형식이 되겠습니다.

getTXT = ExternalInterface.call("Hello", _root.txt);

로 했으니 이것은 돌려받은 값을 getTXT에 저장하겠다는 뜻이겠지요.

 

2. HTML 파트

자바스크립트는 별거 없습니다.

function Hello(msg){

}

안에서 실컷 변수로 가지고 놀다가 return 으로 돌려주면 끝입니다.

정말 사용하기 편하죠?

 

3. Embed 파트

플래시가 브라우져와 바로 소통하기 위해서 사전 조치가 필요합니다.

드래그로 플래시를 HTML 에 삽입하게 되면 기본적인 파라미터들만 붙게 되는데

거기에 추가해줘야하는 것들이 있습니다.

 - <object> 와 <embed> 에 각각 id 와 name 을 지정해준다.

  -> <object ... id="external_flash">

  -> <embed ... name="external_falsh">

이것은 플래시가 하나의 오브젝트로 브라우져에서 명령을 하달받기 위해서입니다.

그냥 이름만 가지고 있으면 됩니다 -_-;;

그리고 <param name="allowScriptAccess" value="always"> 태그와

embed 태그안에 allowScriptAccess="always" swLiveConnect=true 속성을 추가해줍니다.

 

그러면 끝! ==========================================================================================

 

사용법은 생각보다 간단합니다.

ExternalInterface.call 는 플래시 -> 자바스크립트 -> 플래시 이지만

ExternalInterface.addCallback 이라는 함수는

플래시내의 함수를 플래시 밖으로 보내서 자바스크립트가 함수를 가져다 쓸수 있도록 하는 함수입니다.

call 과 addCallback 을 잘 사용하면 자바스크립트와 플래시가 다정하게 사귀는 모습을 보실 수 있을겁니다.

addCallback 은 회사일때문에 아직 테스트를 못해봐서

테스트해보고 오픈강좌에 올려보겠습니다. ^^

참고로 샘플 파일 올려놓겠슴다.

 

 

=================================

=================================

=================================

 

 

 

출처: http://lightness.co.uk/external-interface-examples/

ExternalInterface Examples

Posted on December 14, 2010 by Martin Coulthurst

ExternalInterface is an extremely useful way to pass data between Flash and it’s host web page. Some examples include flagging if Flash content has changed and not been saved before leaving the page, using HTML text in a SWF, and passing cookie data via Flash.

There are three key parts to the ExternalInterface: the Document Object Model (DOM), the SWF, and the External Interface. The DOM is the web page, complete with it’s Javascript. The SWF is the Flash application and the External Interface is the bridge between them.

Passing data out of Flash using ExternalInterface

This first step is straight forward and requires two things: As3 code to call the Javascript, and a matching JS function to handle the call. The Actionscript code looks like this:

import flash.external.ExternalInterface;
ExternalInterface.call("myJavascriptFunction", "some new text variable");

This code passes the data out to the web page. It needs a Javascript function of the same name in the page to receive the data, e.g.

function myJavascriptFunction (data)
{
alert(data);
}

Passing data into Flash using ExternalInterface

Passing data into the SWF application is a little bit more complicated. Again there are two parts: the AS3 code in the SWF and the Javascript in the web page.

In the AS3 code, you first need to set up a method (and its associated function) that the external page will call. This is done using the addCallBack method:

ExternalInterface.addCallback("NameToCallFromJavaScript", myMethod);
private function myMethod(text:String):void
{
trace(text);
}

Note: In order to reach the SWF, the Javascript needs to get a reference to it, and then call it. This can be done using document.getElementById( “mySWF” ).

In the HTML page you need to identify the flash content (“mySWF”) and then call the AS3 method.


<head>
<title>AS3 ExternalInterface Example</title>
<script src="swfobject.js" type="text/javascript"></script>
<script type="text/javascript">
var flashvars = {};
var params = { allowscriptaccess: "sameDomain"};
swfobject.embedSWF("myApp.swf", "mySWF", "960", "600", "10.0.0", "", flashvars, params );
function sendToFlash()
{
document.getElementById( "mySWF" ).NameToCallFromJavaScript( "Text to pass from JS to SWF" );
}
</script>
</head>
<body>
<div id="mySWF"></div>
<a href="#" onClick="sendToFlash();">Send to Flash</a>
</body>
</html>

Note: Flash Player 8+ security features limit the player communications. To allow the swf to communicate with Javascript in HTML pages, the allowScriptAccess param must be set. By default this is set to ‘sameDomain’ which allows scripts only when the SWF resides in the same sub-domain as the host web page. Setting this to ‘always’ allows all scripts to call out from the SWF.

Clicking the link on the page triggers the Javascript. This references the SWF and calls the ExternalInterface method we previously registered, which finally traces out the text we sent.

Flash’s ExternalInterface provides a powerful way to integrate Flash with Javascript, and can be used to extend SWFs by making additional browser data available, and also blend Flash content in a SEO-friendly and standards-compliant way.

More information on ExternalInterface can be found here:

Adobe Devnet Article

Adobe Livedocs

 

 

=================================

=================================

=================================

 

 

 

반응형

 

728x90

 

 

 

 

출처: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/external/ExternalInterface.html

Property Detail

available

property

available:Boolean  [read-only]

Language Version:  ActionScript 3.0
Runtime Versions:  AIR 1.0, Flash Player 9, Flash Lite 4

Indicates whether this player is in a container that offers an external interface. If the external interface is available, this property is true; otherwise, it is false.

Note: When using the External API with HTML, always check that the HTML has finished loading before you attempt to call any JavaScript methods.



Implementation 
    public static function get available():Boolean

More examples

Using the ExternalInterface class
Getting information about the external container


Example  ( How to use this example 

The following example uses the available property to determine whether the player is in a container that offers an external interface.

 

package { import flash.text.TextField; import flash.display.MovieClip; import flash.external.ExternalInterface; public class extint_test extends MovieClip { public function extint_test() { var isAvailable:Boolean = ExternalInterface.available; var availTxt:TextField = new TextField(); availTxt.text = isAvailable.toString(); addChild(availTxt); } } }

marshallExceptions

property  

public static var marshallExceptions:Boolean = false

Language Version:  ActionScript 3.0
Runtime Versions:  AIR 1.0, Flash Player 9.0.115.0, Flash Lite 4

Indicates whether the external interface should attempt to pass ActionScript exceptions to the current browser and JavaScript exceptions to the player. You must explicitly set this property to true to catch JavaScript exceptions in ActionScript and to catch ActionScript exceptions in JavaScript.

Related API Elements

addCallBack()
try..catch..finally statement


Example  ( How to use this example 

The following example creates an ActionScript function and registers it with the containing browser by using the addCallback() method. The new function throws an exception so that JavaScript code running in the browser can catch it. This example also contains atry..catch statement to catch any exceptions thrown by the browser when the throwit() function is called.

 

package { import flash.external.* import flash.net.*; import flash.display.*; import flash.system.System; public class ext_test extends Sprite { function ext_test():void { ExternalInterface.marshallExceptions = true; ExternalInterface.addCallback("g", g); try { ExternalInterface.call("throwit"); } catch(e:Error) { trace(e) } } function g() { throw new Error("exception from actionscript!!!!") } } }

objectID

property  

objectID:String  [read-only]

Language Version:  ActionScript 3.0
Runtime Versions:  AIR 1.0, Flash Player 9, Flash Lite 4

Returns the id attribute of the object tag in Internet Explorer, or the name attribute of the embed tag in Netscape.



Implementation 
    public static function get objectID():String

More examples

Using the ExternalInterface class
Getting information about the external container

Method Detail

addCallback

() method

public static function addCallback(functionName:String, closure:Function):void

Language Version:  ActionScript 3.0
Runtime Versions:  AIR 1.0, Flash Player 9, Flash Lite 4

Registers an ActionScript method as callable from the container. After a successful invocation of addCallBack(), the registered function in the player can be called by JavaScript or ActiveX code in the container.

Note: For local content running in a browser, calls to the ExternalInterface.addCallback() method work only if the SWF file and the containing web page are in the local-trusted security sandbox. For more information, see the Flash Player Developer Center Topic: Security.

Parameters

functionName:String — The name by which the container can invoke the function.
 
closure:Function — The function closure to invoke. This could be a free-standing function, or it could be a method closure referencing a method of an object instance. By passing a method closure, you can direct the callback at a method of a particular object instance.Note: Repeating addCallback() on an existing callback function with a null closure value removes the callback.


Throws

Error — The container does not support incoming calls. Incoming calls are supported only in Internet Explorer for Windows and browsers that use the NPRuntime API such as Mozilla 1.7.5 and later or Firefox 1.0 and later.
 
SecurityError — A callback with the specified name has already been added by ActionScript in a sandbox to which you do not have access; you cannot overwrite that callback. To work around this problem, rewrite the ActionScript that originally called the addCallback()method so that it also calls the Security.allowDomain() method.
 
SecurityError — The containing environment belongs to a security sandbox to which the calling code does not have access. To fix this problem, follow these steps:
  1. In the object tag for the SWF file in the containing HTML page, set the following parameter:<param name="allowScriptAccess" value="always" />
  2. In the SWF file, add the following ActionScript:flash.system.Security.allowDomain(sourceDomain)

More examples

Using the ExternalInterface class
Calling ActionScript code from the container

Related API Elements

flash.system.Security.allowDomain()

call

() method  

public static function call(functionName:String... arguments):*

Language Version:  ActionScript 3.0
Runtime Versions:  AIR 1.0, Flash Player 9, Flash Lite 4

Calls a function exposed by the SWF container, passing zero or more arguments. If the function is not available, the call returns null; otherwise it returns the value provided by the function. Recursion is not permitted on Opera or Netscape browsers; on these browsers a recursive call produces a null response. (Recursion is supported on Internet Explorer and Firefox browsers.)

If the container is an HTML page, this method invokes a JavaScript function in a script element.

If the container is another ActiveX container, this method dispatches the FlashCall ActiveX event with the specified name, and the container processes the event.

If the container is hosting the Netscape plug-in, you can either write custom support for the new NPRuntime interface or embed an HTML control and embed the player within the HTML control. If you embed an HTML control, you can communicate with the player through a JavaScript interface to the native container application.

Note: For local content running in a browser, calls to the ExternalInterface.call() method are permitted only if the SWF file and the containing web page (if there is one) are in the local-trusted security sandbox. Also, you can prevent a SWF file from using this method by setting the allowNetworking parameter of the object and embed tags in the HTML page that contains the SWF content. For more information, see the Flash Player Developer Center Topic: Security.

Note for Flash Player applications: In Flash Player 10 and Flash Player 9 Update 5, some web browsers restrict this method if a pop-up blocker is enabled. In this scenario, you can only call this method successfully in response to a user event (for example, in an event handler for a mouse click or keypress event).

Parameters

functionName:String — The alphanumeric name of the function to call in the container. Using a non-alphanumeric function name causes a runtime error (error 2155). You can use a try..catch block to handle the error.
 
... arguments — The arguments to pass to the function in the container. You can specify zero or more parameters, separating them with commas. They can be of any ActionScript data type. When the call is to a JavaScript function, the ActionScript types are automatically converted into JavaScript types; when the call is to some other ActiveX container, the parameters are encoded in the request message.

Returns

* — The response received from the container. If the call failed– for example, if there is no such function in the container, the interface is not available, a recursion occurred (with a Netscape or Opera browser), or there is a security issue– null is returned and an error is thrown.


Throws

Error — The container does not support outgoing calls. Outgoing calls are supported only in Internet Explorer for Windows and browsers that use the NPRuntime API such as Mozilla 1.7.5 and later or Firefox 1.0 and later.
 
SecurityError — The containing environment belongs to a security sandbox to which the calling code does not have access. To fix this problem, follow these steps:
  1. In the object tag for the SWF file in the containing HTML page, set the following parameter:<param name="allowScriptAccess" value="always" />
  2. In the SWF file, add the following ActionScript:flash.system.Security.allowDomain(sourceDomain)

More examples

Using the ExternalInterface class
Calling external code from ActionScript
Controlling outbound URL access


Example  ( How to use this example 

The following example shows how you can use the ExternalInterface class (flash.external.ExternalInterface) to send a string from Flash Player to the HTML container where it is displayed using the JavaScript alert() function. Example provided by ActionScriptExamples.com.

 

// // Requires: // - A Flash Professional Label component on the Stage with an instance name of "lbl". // - A Flash Professional Button component on the Stage with an instance name of "button". // var xmlResponse:String = "<invoke name=\"isReady\" returntype=\"xml\"><arguments><number>1</number><number>" + stage.stageWidth + "</number><number>" + stage.stageHeight + "</number></arguments></invoke>"; lbl.text = "ExternalInterface.available: " + ExternalInterface.available; lbl.width = 200; button.enabled = ExternalInterface.available; button.addEventListener(MouseEvent.CLICK, button_click); function button_click(evt:MouseEvent):void { ExternalInterface.call("alert", xmlResponse); }

Examples How to use this example

ExternalInterfaceExample.as

 

The following example demonstrates sending data between Flash Player and an HTML container.

 

package { import flash.display.Sprite; import flash.events.*; import flash.external.ExternalInterface; import flash.text.TextField; import flash.utils.Timer; import flash.text.TextFieldType; import flash.text.TextFieldAutoSize; public class ExternalInterfaceExample extends Sprite { private var input:TextField; private var output:TextField; private var sendBtn:Sprite; public function ExternalInterfaceExample() { input = new TextField(); input.type = TextFieldType.INPUT; input.background = true; input.border = true; input.width = 350; input.height = 18; addChild(input); sendBtn = new Sprite(); sendBtn.mouseEnabled = true; sendBtn.x = input.width + 10; sendBtn.graphics.beginFill(0xCCCCCC); sendBtn.graphics.drawRoundRect(0, 0, 80, 18, 10, 10); sendBtn.graphics.endFill(); sendBtn.addEventListener(MouseEvent.CLICK, clickHandler); addChild(sendBtn); output = new TextField(); output.y = 25; output.width = 450; output.height = 325; output.multiline = true; output.wordWrap = true; output.border = true; output.text = "Initializing...\n"; addChild(output); if (ExternalInterface.available) { try { output.appendText("Adding callback...\n"); ExternalInterface.addCallback("sendToActionScript", receivedFromJavaScript); if (checkJavaScriptReady()) { output.appendText("JavaScript is ready.\n"); } else { output.appendText("JavaScript is not ready, creating timer.\n"); var readyTimer:Timer = new Timer(100, 0); readyTimer.addEventListener(TimerEvent.TIMER, timerHandler); readyTimer.start(); } } catch (error:SecurityError) { output.appendText("A SecurityError occurred: " + error.message + "\n"); } catch (error:Error) { output.appendText("An Error occurred: " + error.message + "\n"); } } else { output.appendText("External interface is not available for this container."); } } private function receivedFromJavaScript(value:String):void { output.appendText("JavaScript says: " + value + "\n"); } private function checkJavaScriptReady():Boolean { var isReady:Boolean = ExternalInterface.call("isReady"); return isReady; } private function timerHandler(event:TimerEvent):void { output.appendText("Checking JavaScript status...\n"); var isReady:Boolean = checkJavaScriptReady(); if (isReady) { output.appendText("JavaScript is ready.\n"); Timer(event.target).stop(); } } private function clickHandler(event:MouseEvent):void { if (ExternalInterface.available) { ExternalInterface.call("sendToJavaScript", input.text); } } } }

In order to test the previous ActionScript code, embed the generated SWF file using the following HTML template:

 

 

 

=================================

=================================

=================================

 

 

 

출처: http://www.cyworld.com/poov7/3729437

html

<script>
// 플래시는 java1을 호출하는데, java1은 다른 함수를 호출하도록 등록만하고, 종료
function  java1()
{
    id = setInterval( "javaMain1()", 10 );
}

    
function  javaMain1()
{
    clearInterval( id );
    alert( "하이~" );

}

 

function java2( a, b, c )
{
    var d = a + b + c;
    alert( "합은 " + d );
}


function  java3( a, b )
{
    var c = a + b;
    return  c;
}


function  java4( a, b )
{
    var c = Number( a ) + Number( b );
    return c;
}


//  자바스크립트에서 return을 사용하면, 플래시로 그 값을 받을 수 있다..!!!
function  java5()
{
    id2 = setInterval( "javaMain5()",  10 );
}


function  javaMain5()
{
    clearInterval( id2 );
    var  a = confirm( "오늘 기분 좋아요?" );
    thisMovie( "main" ).flash5( a );
}

 

// 브라우져 체크

function thisMovie(movieName)

{
    if (navigator.appName.indexOf("Microsoft") != -1)

    {
        return window[movieName];
    } else {
        return document[movieName];
    }
}

</script>

 


 

swf

 

call_btn.addEventListener( MouseEvent.MOUSE_DOWN, onDown );
function  onDown( e: MouseEvent ): void
{
    ExternalInterface.call( "java1" );
}

call_btn2.addEventListener( MouseEvent.MOUSE_DOWN, onDown2 );
function  onDown2( e: MouseEvent ): void
{
    ExternalInterface.call( "java2", 5, 2, 7 );
}


// 자바스크립트 호출
// ExternalInterface.call( "자바함수", 매개변수1, 매개변수2, ... );

call_btn3.addEventListener( MouseEvent.MOUSE_DOWN, onDown3 );
function  onDown3( e: MouseEvent ): void
{
    // 넘긴 값의 합을 받아서 result_txt에 표시
    result_txt.text = String( ExternalInterface.call( "java3", 7, 4 ) );
}


// call_btn4를 누르면, a_txt에 입력한 값과 b_txt에 입력한 값을 넘겨서, 이 값을 자바스크립트에서
// 더한 후, 결과를 받아서 c_txt에 표시하도록 ...
call_btn4.addEventListener( MouseEvent.MOUSE_DOWN, onDown4 );
function  onDown4( e: MouseEvent ): void
{
    c_txt.text = String( ExternalInterface.call( "java4", a_txt.text, b_txt.text ) );
}


// ExternalInterface.call()은 동기식으로 동작한다..!!
// 만약 ExternalInterface.call로 팝업창을 호출한 상태에서, 15초동안 반응이 없으면, 오류발생...!!
call_btn5.addEventListener( MouseEvent.MOUSE_DOWN, onDown5 );
function  onDown5( e: MouseEvent ): void
{
    ddd_txt.text = String( ExternalInterface.call( "java5" ) );
}

 

// flash    --> javascript 호출 ::: ExternalInterface.call
// javascript --> flash 호출   ::: ExternalInterface.addCallback

ExternalInterface.addCallback( "flash5", flash5Main );

function  flash5Main( a: String ): void
{
    ddd_txt.text = a;
}

 

 

=================================

=================================

=================================

 

 

 

출처: http://ahikuya.tistory.com/1

 

플래시에서 JSON 데이터를 가져오는 방법은 두가지가 있다.
첫번째 방법은 URLLoader 를 이용해 load 하여 사용하는 방법이고
두번째 방법은 JQuery를 통해 로드된 데이터를 가져다 쓰는 방법이다.
 
[URLLoader 를 이용]
1. URLLoader를 통해 데이터를 불러온다.
2. 로드 완료 되면 com.adobe.serialization.json.JSON 으로 디코딩 하여 사용한다.

- 보통은 이 방법을 사용하면 된다.


[JQuery 를 이용 A]
1. $(document).ready() 를 통해 DOM이 준비 되면
2. jQuery.getScript(url, [, fn]) 을 호출하여 JSON데이터를 로드한다.
3. 로드 완료 되면 플래시의 콜백 함수를 호출하여 실행시킨다.
- 플래시의 메소드가 호출 되기 위해서는 먼저 플래시의 컨텐츠가 셋팅되어 있어야 한다.(보장 할수 있나?)


[JQuery 를 이용 B]
1. 플래시가 셋팅되면 자바스크립트를 호출을 통해 jQuery.getScript(url, [, fn]) 을 호출하여 JSON데이터를 로드한다.
2. 로드 완료 되면 플래시의 콜백 함수를 호출하여 실행시킨다.
- 절차가 너무 길다는 단점이 있다.
  (플래시 셋팅완료 -> 자바스크립트 호출 -> JSON데이터 로드 -> 데이터로드 완료 -> 플래시 콜백함수 호출)

JQuery를 이용해야 하는 경우는 플래시가 아닌 다른 곳에서 이미 그 데이터를 사용하기 위해 로드를 실행시켰을 경우이다.
따라서 A방법을 통한 데이터 Access가 요구된다.
그렇다면 JSON데이터가 로드 완료 되었을때 플래시 컨텐츠가 준비되어 있음을 어떻게 보장해야 할까?

 

 

=================================

=================================

=================================

 

 

 

출처: http://blog.naver.com/lhk0812h?Redirect=Log&logNo=100123553301

 

.call

http://cafe.naver.com/flashdev.cafe?iframe_url=/ArticleRead.nhn%3Farticleid=8089&

 

.addCallback

http://cafe.naver.com/flashdev.cafe?iframe_url=/ArticleRead.nhn%3Farticleid=8093

 

자바스크립트상에서 플래시는 오브젝트 객체.. 바로 아이디를 적으면 인식(window 객체 안에 포함)

html 안에서 플래시의 allowScriptAccess 부분을(2군데) 모두 always로 바꾸고 테스트 할것

 -( 더 알아볼 부분.. 1.플래시 부분에서 다이나믹텍스트 폰트 임베드 2.자바스크립트에서 한글 문자 리턴 안되는 부분)

 

플래시 부분

 

stop();
Security.allowDomain("*");
callJavaBtn.buttonMode = true;
callJavaBtn.mouseChildren = false;
callJavaBtn.addEventListener(MouseEvent.MOUSE_DOWN, MouseDown);
function MouseDown(e:MouseEvent){
 inputText.text = "gks한굴 123";
 ExternalInterface.call("changeTitle", "플래시 맘대로 제목~질~");
}

 


function restore(newMessage:String){
 inputText.text = newMessage;
}
ExternalInterface.addCallback("restore" , restore);

 

자바스크립트 부분

 

<script language ="javascript">


function changeTitle(text){

 document.title = text;

//한글 안되네??

 alert("title changed");
 document.title = "basic name";
 myFlash.restore("it has been restored");


}


</script>

[출처] as3.0 externalInterface ( javascript 연동)|작성자 lhk0812h

 

 

=================================

=================================

=================================

 

 

 

출처: http://www.cyworld.com/poov7/3727881

// 자바스크립트 연동 
AS1.0, AS2.0 :   getURL( "javascript:자바함수()" );  -> navigateToURL 사용불가

 

HTML( swf ) , JSP( swf ), PHP( swf ), ASP( swf ), VB( swf ), VC( swf ), DELPHI( swf )

 

Wrapper( swf )

 

swf 파일과 Wrapper와의 통신 
- ExternalInterface.call( ) : 동기식으로 동작
- fscommand( ) : 비동기식으로 동작 
 
* 동기식( synchronous )  <---> 비동기식 ( Asynchronous )
 
동기식 : 기다려준다.. ( 배려~ ),   비동기 : 기다리지 않음 
 
플래시 :  <<<  동기식  >>>> VS 비동기식
 
a = 20;
b = 30;
a = 40;
c = a + b;
 
단, 외부와의 연동은 << 비동기식 >>이다..!!
 
var loader: Loader = new Loader();
this.addChild( loader );
loader.contentLoaderInfo.addEventListener( Event.COMPLETE, onComplete );
loader.load( new URLRequest( "http://www.naver.com/abc.jpg" ) );
 
function  onComplete( e: Event ): void
{
    loader.width = 200;
    loader.height = 200;
}

 

 

=================================

=================================

=================================

 

 

반응형


관련글 더보기

댓글 영역