Using Flash Movies with JavaScript and DHTML


The ActionScripting features of Flash 8 have once again increased the range of interactive and dynamic possibilities for Flash movies on the Web. Prior to Flash Player 4, Flash movies could interact with external HTML or scripts only through the fscommand() action. This meant mapping commands and variables to JavaScript, which, in turn, passed information to the document object model of DHTML, Java applets, or CGI (Common Gateway Interface) scripts. Now that Flash movies can directly send and receive data to server-side CGI scripts, just about anything can be done within the Flash movie. If you want to directly communicate with the Web browser or the HTML document, you need to use JavaScript with either fscommand() actions or the new ExternalInterface API (Application Programming Interface) introduced with Flash Player 8.

New Feature 

The ExternalInterface API is part of the flash.external class, and is available in Flash Player 8 or higher. This new set of actions (collectively known as an API) enables you to communicate directly with the Flash movie's hosting environment. Unlike the older fscommand() action, the ExternalInterface API enables you to receive data from the hosting environment immediately, without setting up callback handlers.

A Word of Caution to Web Developers

This section covers the new ExternalInterface API actions, which, when used in Flash movies on Web pages, are supported by the following browsers:

  • Internet Explorer 4.0 and higher for Windows 98/ME/2000/XP

  • Mozilla 1.7.5 and higher

  • Mozilla FireFox 1.0 and higher

  • Apple Safari 1.3 and higher

Caution 

At the time of this writing, ExternalInterface API actions are not available yet in Opera.

Our coverage of the ExternalInterface API assumes that you have a working knowledge of JavaScript and Flash ActionScript. If you don't know how to add actions to frames or buttons, please read Chapter 18, "Understanding Actions and Event Handlers." If you don't know JavaScript, you can still follow the steps to the tutorials and create a fully functional Flash-JavaScript movie. However, because this isn't a book on JavaScript, we don't explain how JavaScript syntax or functions work.

Understanding How Flash Movies Work with JavaScript

As we mentioned earlier, Flash Player has a new class called ExternalInterface. This class has methods that can invoke commands (passing optional arguments, or parameters) from a Flash movie to its hosting environment, such as JavaScript in a Web browser. What does this mean for interactivity? The ExternalInterface API offers the capability to have any Flash event handler (Button instance, onClipEvent(), frame actions, and so on) initiate an event handler in JavaScript. Although this may not sound too exciting, you can use ExternalInterface actions to trigger anything that you would have used JavaScript alone to do in the past, such as updating HTML-form text fields, changing the visibility of HTML elements, or switching HTML background colors on the fly. We look at these effects in the next section.

Flash movie communication with JavaScript is not a one-way street. You can also monitor and control Flash movies with JavaScript. Just as JavaScript treats an HTML document as an object and its elements as properties of that object, JavaScript treats a Flash movie as it would any other element on a Web page. Therefore, you can use JavaScript functions and HTML hyperlinks (<a href> tags) to control Flash movie playback.

Note 

For JavaScript to receive Flash events, you need to make sure that the attribute allowScriptAccess for the <object> and <embed> tags is set to "sameDomain" or "always". By default, most Flash 8 HTML templates have this set to "sameDomain". If you're testing your Flash movies and HTML documents locally, you should temporarily switch the value to "always"; otherwise, JavaScript will not receive the events from the Flash movie.

Web Resource 

This edition of the Flash Bible features coverage of the new ExternalInterface API available in Flash Player 8. If you'd like to read more about the older fscommand() method of sending data to and from the Flash Player and JavaScript, refer to the archived document at www.flashsupport.com/archive.

Changing HTML Attributes

In this section, we show you how to dynamically change the bgcolor attribute of the <body> tag with an ExternalInterface action from a Flash movie while it is playing in the browser window. In fact, the background color will change a few times. Then, after that has been accomplished, you learn how to update the text field of a <form> tag to display what percent of the Flash movie has been loaded.

On the CD-ROM 

Before you start this section, make a copy of the Flash document countdown_starter.fla located in the ch22/ExternalInterface folder of this book's CD-ROM. This is a starter document to which you will add ActionScript code.

Adding ExternalInterface Actions to a Flash Movie

Open the countdown_starter.fla Flash document from this book's CD-ROM, and use Control ð Test Movie to play the Flash.swf file. You should notice that the filmstrip count down fades to white, and then to near-black, and then back to its original gray color. This countdown continues to loop until the entire first scene has loaded into the Flash Player. When the first scene has loaded, playback skips to a video clip of Robert swinging around and around. There's more to the Flash movie, but for now, that's all you need to deal with.

Our goal for this section of the tutorial is to add function calls to specific keyframes in the countdown_starter.fla document. When the Flash Player plays the frame with a function call, the Player sends a command and argument string to JavaScript. JavaScript then calls a function that changes the background color to the value specified in the argument string of the function. To be more exact, you'll create a function named changeBgColor in ActionScript. This function, when invoked (or "called"), will invoke a corresponding function named changeBgColor in the JavaScript code created later in this section. You'll add code to invoke the changeBgColor() function to the frames where the color fades to white, black, and gray. When the Flash movie changes to these colors, JavaScript will change the HTML background colors.

Here's the process:

  1. Select frame 1 of the actions layer, and open the Actions panel (F9, or Option+F9 on Mac). In the Script pane, add the following code. Make sure you are not in Script Assist mode. This code, written in ActionScript 2.0 syntax, imports the ExternalInterface class and creates a changeBgColor() function that accepts one argument named sColor. This argument is passed to the call() method of the ExternalInterface class. The call() method takes one or more parameters. The first argument is always the name of the method (or function) to call in the hosting environment, and subsequent arguments are passed to the called method. In this example, you only need to pass one argument, sColor, to the JavaScript host environment.

     import flash.external.ExternalInterface; function changeBgColor(sColor:String):Void {    ExternalInterface.call("changeBgColor", sColor); } 

  2. On frame 16 of the Main Timeline, add a keyframe on the actions layer. With the keyframe selected, open the Actions panel (F9, or Option+F9 on Mac). Type the following action into the Script pane:

     changeBgColor("#FFFFFF"); 

    This action invokes the changeBgColor() function you defined on frame 1 in the previous step. The argument string #FFFFFF is passed to that function. The Flash function named changeBgColor() will pass that argument to the hosting environment's changeBgColor() function as well, changing the HTML background color to white.

  3. On frame 20, add another action to the corresponding keyframe on the actions layer. With frame 20 selected, open the Actions panel and type the following code:

     changeBgColor("#333333"); 

    The argument "#333333" will be used to change the HTML background color to a dark gray.

  4. On frame 21 of the actions layer, follow the same instructions as you did for Step 3, except use "#9E9E9E" for the argument string. This changes the HTML background color to the same color as the Flash movie countdown graphic.

  5. On frame 66 of the actions layer, add another action invoking the changeBgColor() function. (Add this action after the existing action on this frame.) This time, use an argument string of "#000000", which changes the HTML background color to black.

  6. Now that you've added several actions, try them out in the browser. Save the document as countdown_100.fla, and open the Publish Settings dialog box (for more information on Publish Settings, refer to Chapter 21, "Publishing Flash Movies"). In the Formats tab, make sure both the Flash and HTML format check boxes are selected. Change the Flash filename to countdown.swf, and leave the HTML filename as countdown_100.html. Click OK to close the Publish Settings dialog box. Choose the File ð Publish command to export the Flash movie and HTML document.

Next, you'll build the JavaScript code that will be added to the HTML file published by Flash.

Enabling JavaScript for Flash Movies

In this section, you add the necessary JavaScript to make the ExternalInterface.call() action work in the browser. Remember, you added this action to the changeBgColor() function on frame 1 of the Flash movie. What follows in Listing 22-3 is the JavaScript code that defines the custom function changeBgColor that we have created for you. Add this code to the countdown_100.html file you published in the last section.

Listing 22-3: The JavaScript Code to Enable the ExternalInterface Actions

image from book
 5.    <script type=" text/javascript" language=" javascript"> 6.    <!-- 7.    function changeBgColor(hexColor){ 8.       document.bgColor = hexColor; 9.    } 10.   //--> 11.   </script> 
image from book

Note 

The line numbers reflect the actual line numbers in the HTML document.

The following is a line-by-line explanation of the code:

  1. This HTML tag initializes the JavaScript code.

  2. This string of characters is standard HTML comment code. By adding this after the opening <script> tag, non-JavaScript browsers ignore the code. If this string wasn't included, text-based browsers such as Lynx might display JavaScript code as HTML text.

  3. This is where the function changeBgColor() is defined. Remember that the changeBgColor() function in the Flash ActionScript specifies "changeBgColor" in the ExternalInterface.call() method. There is one argument defined for the function: hexColor, representing the hexadecimal color value passed from the Flash movie.

  4. This line of code passes the argument hexColor to the document.bgColor property, which controls the HTML background color.

  5. This line of code ends the function defined in line 7.

  6. This end comment in line 10 closes the comment started in line 6.

  7. The closing </script> tag ends this portion of JavaScript code.

That's it! We also added <center> tags around the <object> and <embed> tags to center the Flash movie on the HTML page, and we changed the allowScriptAccess parameter and attribute in the <object> and <embed> tags, respectively, to "always". Once you've manually added the custom lines of JavaScript code, you can load the HTML document into either Internet Explorer or a Mozilla-compatible browser (see the caveats mentioned at the beginning of this section). When the Flash Player comes to the frames with changeBgColor() actions, the HTML background should change along with the Flash movie. Next, you add a <form> element that displays the percentage of the Flash movie that has loaded into the browser window.

On the CD-ROM 

You can find this version of the countdown_100.fla document in the ch22/ExternalInterface folder on this book's CD-ROM. You will also find countdown.swf and a fully JavaScripted HTML document called countdown_100.html.

Adding a PercentLoaded() Method

With Flash Player 8 and the ExternalInterface API, JavaScript can also communicate back to the Flash movie. In the Flash movie, you need to define callback handlers using the ExternalInterface.addCallback() method. This method lets you set up custom functions that are exposed to the hosting environment.

In this section, you create a JavaScript percentLoaded() method to display the Flash movie's loading progress update as a text field of a <form> element. First, you add the necessary ExternalInterface action and custom function to the Flash movie, next you add HTML <form> elements, and then you add the appropriate JavaScript.

  1. Open the countdown_100.fla file that you modified in the previous section. Select frame 1 of the actions layer, and open the Actions panel (F9, or Option+F9 on Mac). Add the following code after the existing code in the Script pane. Do not type the image from book character as it denotes a continuation of the same line of code.

     function getPercentLoaded():Number {    var lb:Number = this.getBytesLoaded();    var tb:Number = this.getBytesTotal();    return Math.floor((lb/tb)*100); } ExternalInterface.addCallback("getPercentLoaded", this,image from book getPercentLoaded); 

    This function, getPercentLoaded(), does not use any arguments. The purpose of the getPercentLoaded() function is to return the percent loaded of the Flash movie file (.swf). After the function is declared, it is exposed to JavaScript with the ExternalInterface.addCallback() method. This method takes three arguments: the name you want to use in JavaScript to call the Flash function ("getPercentLoaded", although you could specify a different name here to use in JavaScript if you preferred), the scope of the Flash function (this, which is the Main Timeline of the Flash movie), and the Flash function name that will be invoked when JavaScript calls the function named as the first argument (getPercentLoaded).

  2. Save your Flash document as countdown_complete.fla, and open the Publish Settings dialog box. In the Formats tab, uncheck the HTML file format, and leave the Flash movie filename to countdown.swf. Then publish your Flash movie.

  3. In a text editor such as Macromedia Dreamweaver, Notepad, or TextEdit, open the countdown_100.html document from the previous section. Immediately resave this document as countdown_complete.html to overwrite the one published from Flash 8.

  4. Add the following HTML after the <object> and <embed> tags:

     <form method=" post" action="" name=" flashPercent" style=" display:show">   <input type=" text" name=" tPercent" size="5"   style=" display:show" /> </form> 

    The code in Step 4 uses two name attributes so that JavaScript can recognize them. Also, the DHTML style attribute assigns a display:show value to both the <form> and <input> tags.

  5. Add the JavaScript code shown in Listing 22-4 to your HTML document after the changeBgColor() function. The following percentLoaded function tells the browser to update the <form> text field with the percent of the Flash movie currently loaded. When the value is greater than or equal to 100, then the text field reads 100 percent and disappears after two seconds. This code also declares a thisMovie() function, which returns a reference to the Flash object in the <object> or <embed> tag. The thisMovie() function is used in the percentLoaded() function to call the Flash movie's getPercentLoaded() function you wrote in Step 1 of this section, to retrieve the loaded percent of the Flash movie. After the percentLoaded() function is declared in JavaScript, you use the setInterval() function in JavaScript to continuously invoke the percentLoaded() function, every 100 milliseconds. This interval is cleared when the Flash movie is fully loaded. (The indicates a continuation to the same line of code. Do not type this character in your code.)

    Listing 22-4: The JavaScript Code for the percentLoaded() Function

    image from book
     function thisMovie(movieName) {     var isIE = navigator.appName.indexOf("Microsoft") != -1;     return (isIE) ? window[movieName] : document[movieName]; } function percentLoaded(){      var nPercent = thisMovie("countdown").getPercentLoaded();      if(nPercent >= 100){              document.flashPercent.tPercent.value= "100 %";              setTimeout("document.flashPercent.tPercent.style.display =image from book                  'none'", 2000);              setTimeout("document.flashPercent.style.display = ‘none'", 2000);              clearInterval(nCheckID);      } else {              document.flashPercent.tPercent.value = nPercent + "%" ;      } } var nCheckID = setInterval(percentLoaded, 100); 
    image from book

    Note 

    The thisMovie() function code is taken directly from Macromedia's ExternalInterface API example code shown in the documentation that is accessed through the Help panel. Also, you might notice that JavaScript has some of the same function names as Flash ActionScript does. Both JavaScript and ActionScript have a setInterval() function to enable you to call a function continuously at a specific interval.

  6. Save the HTML document and load it into a browser. If you run into errors, check your JavaScript syntax carefully. A misplaced ; or } can set off the entire script. Also, the function names specified in the Flash ActionScript code and the JavaScript code are case-sensitive and must be exactly the same. If you continue to run into errors, compare your document to the countdown_complete.html document on this book's CD-ROM. We also recommend that you test the preloading functionality from a remote Web server. If you test the file locally, the Flash movie loads 100 percent instantaneously.

Caution 

Remember that this type of interactivity won't work on all browsers, and it requires the use of Flash Player 8.

Okay, that wasn't the easiest task in the world, and, admittedly, the effects might not have been as spectacular as you may have thought. Now that you know the basics of Flash and JavaScript interactivity, however, you can take your Flash movie interactivity one step further.

Web Resource 

We'd like to know what you think about this chapter. Visit www.flashsupport.com/feedback to send us your comments.




Macromedia Flash 8 Bible
Macromedia Flash8 Bible
ISBN: 0471746762
EAN: 2147483647
Year: 2006
Pages: 395

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