Recipe 22.1. Calling JavaScript Functions


Problem

You want to call a JavaScript function from ActionScript.

Solution

Use ExternalInterface.call( ).

Discussion

Use the ExternalInterface.call( ) method to make synchronous calls to JavaScript functions from ActionScript. The call( ) method requires at least one parameter as a string specifying the name of the function to call:

ExternalInterface.call("changeTitle");

The function must be defined in the HTML page with the same name:

<script language="JavaScript">     function changeTitle(title) {         if(title == undefined) {             title = "New Title";         }         window.title = title;     } </script>

If the JavaScript function accepts parameters, you can pass values to it by adding additional parameters when calling the call( ) method. For example, the following passes a value to the changeTitle( ) function:

ExternalInterface.call("changeTitle", "ActionScript 3.0 Cookbook");

Since call( ) is synchronous, any values returned by the JavaScript function are immediately returned to ActionScript. That means you can assign the return value from a call to a variable. The following ActionScript illustrates how that can work:

var title:String = ExternalInterface.call("getTitle");

The JavaScript function for the preceding ActionScript call might look like:

<script language="JavaScript">     function getTitle(  ) {         return window.title;     } </script>

ExternalInterface works for the following browsers:

  • Internet Explorer 5.0+ (Windows)

  • Netscape 8.0+ (Windows and Mac OS X)

  • Mozilla 1.7.5+ (Windows and Mac OS X)

  • Firefox 1.0+ (Windows and Mac OS X)

  • Safari 1.3+ (Mac OS X)

If you need to support a browser that ExternalInterface does not work with, you can still make calls to JavaScript functions. However, you must then use the flash.net.navigateToURL( ) function.

The navigateToURL( ) function is asynchronous, meaning it does not return a value. To call a JavaScript function using navigateToURL( ) you must use a flash.net URLRequest object that has a value using the javascript protocol. The following is an example that calls the JavaScript alert( ) function:

var request:URLRequest = new URLRequest("javascript:alert('example');"); navigateToURL(request);

See Also

Recipe 22.2




ActionScript 3. 0 Cookbook
ActionScript 3.0 Cookbook: Solutions for Flash Platform and Flex Application Developers
ISBN: 0596526954
EAN: 2147483647
Year: 2007
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net