Calling JavaScript Functions from ActionScript


There are potentially many reasons to call JavaScript functions from a Flash movie embedded within an HTML page. JavaScript has access to data that is not immediately accessible to Flash Player. For example, JavaScript can determine which browser is being used. It's possible that you might want to capture that data and send it to the server for logging purposes. By calling a JavaScript function from Flash, it's possible to retrieve that data and then you can use standard ActionScript APIs (LoadVars, XML, and so on) to send that data to the server. Another possibility that you'll see in the first task of this chapter is that you can call JavaScript functions from Flash to use JavaScript functionality that's not available natively within ActionScript.

Regardless of what you want to accomplish by calling JavaScript functions from Flash, the way in which you make the call is the same. The ExternalInterface.call() method is a static method that requires at least one parameter specifying the name of the function to call. The function name must be specified as a string, and the value must be the name of the function in the container (that is, the JavaScript function) that you want to call. The following code calls a function named testFunction():

    ExternalInterface.call("testFunction");


You can pass parameters to the JavaScript function by adding them to the parameter list of the ExternalInterface.call() method. For example, if you want to pass four string parameters to testFunction(), the code might look something like the following:

   ExternalInterface.call("testFunction", "a", "b", "c", "d");


As a simple example, the following code opens a JavaScript alert window with a message that says "This alert was opened by ExternalInterface.":

    ExternalInterface.call("alert", ¬       "This alert was opened by ExternalInterface.");


Note that alert() is a standard, built-in JavaScript function that opens a new alert window.

One feature that ExternalInterface has that previous Flash-to-JavaScript communication options didn't have is that the call() method is synchronous, so if the JavaScript function returns a value, it is returned by the call() method. For example, if testFunction() is defined so that it returns a string, the following code would assign the return value to a variable called browserStr:

   var browserStr:String = ExternalInterface.call("testFunction");





Macromedia Flash 8 ActionScript Training from the Source
Macromedia Flash 8 ActionScript: Training from the Source
ISBN: 0321336194
EAN: 2147483647
Year: 2007
Pages: 221

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