ProblemYou want to call a JavaScript function from ActionScript. SolutionUse ExternalInterface.call( ). DiscussionUse 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:
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 AlsoRecipe 22.2 |