View comments | RSS feed
Packageflash.external
Classpublic final class ExternalInterface
InheritanceExternalInterface Inheritance Object

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

The ExternalInterface class is the External API, an application programming interface that enables straightforward communication between ActionScript and the Flash Player container– for example, an HTML page with JavaScript. Adobe recommends using ExternalInterface for all JavaScript-ActionScript communication.

You can call an ActionScript function in Flash Player, using JavaScript in the HTML page. The ActionScript function can return a value, and JavaScript receives it immediately as the return value of the call.

This functionality replaces the fscommand() method.

Use the ExternalInterface class in the following combinations of browser and operating system:

BrowserOperating SystemOperating System
Internet Explorer 5.0 and later Windows  
Netscape 8.0 and later Windows  MacOS 
Mozilla 1.7.5 and later Windows  MacOS 
Firefox 1.0 and later Windows  MacOS 
Safari 1.3 and later  MacOS 

Flash Player for Linux version 9.0.31.0 and later supports the ExternalInterface class in the following browsers:

Browser
Mozilla 1.7.x and later
Firefox 1.5.0.7 and later
SeaMonkey 1.0.5 and later

The ExternalInterface class requires the user's web browser to support either ActiveX® or the NPRuntime API that is exposed by some browsers for plug-in scripting. Even if a browser and operating system combination are not listed above, they should support the ExternalInterface class if they support the NPRuntime API. See http://www.mozilla.org/projects/plugins/npruntime.html.

Note: When embedding SWF files within an HTML page, make sure that the id and name attributes of the object and embed tags do not include the following characters:

 . - + * / \
 

From ActionScript, you can do the following on the HTML page:

From JavaScript on the HTML page, you can:

Flash Player does not currently support SWF files embedded within HTML forms.

Note: Adobe AIR currently does not support the ExternalInterface class.

View the examples

See also

flash.system.fscommand()
External API requirements and advantages
Using the ExternalInterface class


Public Properties
 PropertyDefined By
  available : Boolean
[static] [read-only] Indicates whether this player is in a container that offers an external interface.
ExternalInterface
 Inheritedconstructor : Object
A reference to the class object or constructor function for a given object instance.
Object
  marshallExceptions : Boolean = false
[static] Indicates whether the external interface should attempt to pass ActionScript exceptions to the current browser and JavaScript exceptions to Flash Player.
ExternalInterface
  objectID : String
[static] [read-only] Returns the id attribute of the object tag in Internet Explorer, or the name attribute of the embed tag in Netscape.
ExternalInterface
 Inheritedprototype : Object
[static] A reference to the prototype object of a class or function object.
Object
Public Methods
 MethodDefined By
  
addCallback(functionName:String, closure:Function):void
[static] Registers an ActionScript method as callable from the container.
ExternalInterface
  
call(functionName:String, ... arguments):*
[static] Calls a function exposed by the Flash Player container, passing zero or more arguments.
ExternalInterface
 Inherited
Indicates whether an object has a specified property defined.
Object
 Inherited
Indicates whether an instance of the Object class is in the prototype chain of the object specified as the parameter.
Object
 Inherited
Indicates whether the specified property exists and is enumerable.
Object
 Inherited
Sets the availability of a dynamic property for loop operations.
Object
 Inherited
Returns the string representation of the specified object.
Object
 Inherited
Returns the primitive value of the specified object.
Object
Property Detail
availableproperty
available:Boolean  [read-only]

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

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

See also


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);
      }
    }
  }
  
marshallExceptionsproperty 
public static var marshallExceptions:Boolean = false

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

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

See also


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 a try..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!!!!") }
    }
}
objectIDproperty 
objectID:String  [read-only]

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

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

See also

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

Registers an ActionScript method as callable from the container. After a successful invocation of addCallBack(), the registered function in Flash 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 following:

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.


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)

See also

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

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

Calls a function exposed by the Flash Player 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 Flash Player within the HTML control. If you embed an HTML control, you can communicate with Flash 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 following:

Parameters

functionName:String — The alphanumeric name of the function to call in the container.
 
... 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)

See also

Examples How to use examples
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:
 <!-- saved from url=(0014)about:internet -->
 <html lang="en">
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title>ExternalInterfaceExample</title>
 <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("ExternalInterfaceExample").sendToActionScript(value);
     }
     function sendToJavaScript(value) {
         document.forms["form1"].output.value += "ActionScript says: " + value + "\n";
     }
 </script>
 </head>
 <body onload="pageInit();">
 
     <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
             id="ExternalInterfaceExample" width="500" height="375"
             codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab">
         <param name="movie" value="ExternalInterfaceExample.swf" />
         <param name="quality" value="high" />
         <param name="bgcolor" value="#869ca7" />
         <param name="allowScriptAccess" value="sameDomain" />
         <embed src="ExternalInterfaceExample.swf" quality="high" bgcolor="#869ca7"
             width="500" height="375" name="ExternalInterfaceExample" align="middle"
             play="true" loop="false" quality="high" allowScriptAccess="sameDomain"
             type="application/x-shockwave-flash"
             pluginspage="http://www.macromedia.com/go/getflashplayer">
         </embed>
     </object>
 
     <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>
 




 


Comments


No screen name said on Jun 20, 2007 at 9:59 AM :
Hi,
I'd like to use ExternalInterface.call() method without allowScriptAccess in an HTML page. Is it possible?
No screen name said on Jan 15, 2008 at 1:09 PM :
for all those developers who goin crazy about the fact, that the ExternalInterface.call() method don't work in ie7..

YOU HAVE TO SET THE 'id' attribute of the 'object' tag when embedding the .swf!!!!!!

hope the helps

gerdy
williamhannah said on Jan 15, 2008 at 6:45 PM :
I ran into a problem with ExternalInterface, IE, and using the flash embedding script SWFObject.

The problem is that the check in the JS function thisMovie(movieName) is returning window[movieName] for IE, which will not exist if using SWFObject. It took me a while to figure this out (my JS call was failing silently), so I thought I would pass this on before someone else has to try and debug JS in IE.

The solution was to always return document[movieName] in the function (or just use document[moveName] whenever thisMovie is called)
Dan Zen said on Jan 17, 2008 at 7:57 PM :
ExternalInterface would not work for me in IE7 until I added a delay before I called the addCallback() in Flash. I just set a Timer to 50ms.

It also did not seem to work in IE7 if I called the JavaScript and ActionScript functions the same name.

Here is working code:
http://imm.sheridanc.on.ca/code/communication.html
Epskampie said on Jan 27, 2008 at 2:55 PM :
Thanks a lot for the tip gerdy,
setting the id on the object tag works brilliantly to restore the Externalinterface.call() functionality on internet explorer 7.
No screen name said on Feb 29, 2008 at 7:07 PM :
I am using swfobject to load my flash file. It appears that ExternalInterface.addCallback must be called after the main sprite is added to the stage (after the ADDED_TO_STAGE event) for it to work correctly. This is the reason why Dan Zen need the delay workaround. Can someone from Adobe please verify whether this observation is true? If it is so, please update the documentation for addCallback.
No screen name said on Mar 26, 2008 at 12:51 PM :
Thanks Dan Zen! I was having a nonsense javascript error ('Incompatible type') in IE7 while trying to use a method from my swf. The thing was: I named the method 'loadMovie' ine the ExternalInterface.addCallback. And I was using a js function also called 'loadMovie' to access it.

After readind your post, I changed the ExternalInterface callback name to 'loadFLV' and, bingo, it worked. Heck if I, or anybody else, has any idea why.
AlHolden said on Apr 5, 2008 at 11:36 PM :
IE 7 will also throw an "object not defined" error on ExternalInterface.call(s) when your swf is contained within form tags.
I guess it's not smart enough to look in that part of the DOM, or perhaps a result of some more "security".
No screen name said on Apr 10, 2008 at 9:43 AM :
It seems that when using the marshallExceptions property, you must set the compiler strict mode to false. If strict mode is not set to false you will get the following error:

Error: Access of possibly undefined property marshallExceptions through a reference with static type Class.
supersumo1 said on Apr 19, 2008 at 10:54 AM :
I don't get what i'm supposed to set fo the 'id' attribute to make this work in IE7....i just gave it an arbitrary name....does it have to be something specific?

When I view my movie in IE7 and click the button that should call the ExternalInterface, the bottom of the browser say "Error on Page"

I'm confused....it works great in FF...
Jasconius said on Apr 30, 2008 at 10:37 AM :
Does ExternalInterface not work with Safari 3.1 for Windows? I have some
code that uses it and its working fine in IE7 and Firefox, dead in Safari.
No screen name said on May 9, 2008 at 12:36 PM :
Ran into a bug in IE. You can't use "play" or "stop" when registering callbacks through "ExternalInterface.addCallback()". It'll work in Safari and Firefox, but not IE6 or IE7.

You'll get the error on line 48 (of what? Who knows, thanks IE) "object does not support this property". Debugging doesn't make any sense, but whatever.

Just rename the callback something other than "play" or "stop" and everything works peachy.

-- ian
No screen name said on May 19, 2008 at 7:25 PM :
I agree, this appears to be broken in Safari 3.1.
SolitonMan said on Jun 27, 2008 at 7:23 AM :
I've not been able to get this to work completely. I can send messages from ActionScript to JavaScript, but trying to send messages to ActionScript from JavaScript fails. The error message I get is

Error calling method on NPObject! [plugin exception: Error in ActionScript. Use a try/catch block to find error].

I've added a try/catch block to the sendToActionScript function in my HTML page, but I'm kind of stymied about what else to do. All that the try/catch block did was to allow the action to fail with an alert box instead of the browser default error handling. It hasn't helped me understand why this is failing in the first place.

I'm trying this in IE 7 and Mozilla Firefox 2. The messages come from the SWF to the HTML textarea without problem, but the data just won't get into the SWF. I really need to be able to send data in, because I'm working on a system in whcih I need to account for users closing their browser window instead of logging out of the system, and in order to do that I need to trigger events within Flash from HTML. If anyone has any ideas I'd really appreciate hearing them. Thanks!

Regards,
Dave Spaar

 

RSS feed | Send me an e-mail when comments are added to this page | Comment Report

Current page: http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/external/ExternalInterface.html