Chapter 19. Integrating Flash Content with Web Pages

IN THIS CHAPTER

  • Defining HTML tags and attributes for the Flash Player

  • Detecting the Flash Player plug-in or ActiveX control with SWFObject

  • Sending commands with the ExternalInterface API to JavaScript

If you're not one for automated HTML production by using templates, this chapter is for you. In this chapter, I teach you the ins and outs of the <object> and <embed> tags, as well as some tips on how to check for the Flash Player with Flash CS5's detection features or SWFObject. At the end of this chapter, I examine how Flash movies can interact with JavaScript and DHTML (Dynamic HTML) by using the new ExternalInterface actions from Flash.

Note

Many thanks to Geoff Stearns for his ongoing commitment to provide one of the best open source Flash Player detection scripts, SWFObject, to the Flash community. You can find more information about SWFObject later in this chapter.

Writing Markup for Flash Movies

In Chapter 18, you learn how to use the Publish feature, which included automated HTML templates. These templates created the necessary HTML tags to display Flash movies on Web pages. In this section, I discuss the use of Flash movies in your handwritten HTML documents. You can also use this information to alter HTML documents created by the Publish feature.

Note

In the following code examples, I use an asterisk (*) when displaying optional parameters that are not in the default options that are enabled in the Flash Only HTML template. I also use the term plug-in to mean both the Mozilla-compatible plug-in and the ActiveX control for Flash Player 10.

You can use two tags to place Flash movies on a Web page (such as an HTML document): <object> and <embed>. You need to include both of these plug-in tags in HTML documents, as each tag is specific to a browser: <object> for Internet Explorer (IE) on Windows and <embed> for Mozilla-compatible browsers on Windows and Mac. Each tag works similarly to the other, with some slight differences in attribute names and organization. Remember that if both sets of tags are included with the HTML, only one set of tags is actually read by the browser, depending on which browser is used to view the Web page. Without these tags, the browser cannot display Flash movies with other HTML elements such as images and text.

Using the <object> tag

Microsoft Internet Explorer for Windows and any browser that adheres to the HTML 4.01 specification from the World Wide Web Consortium (W3C) use this tag to enable the Flash Player ActiveX control (Internet Explorer for Windows) or plug-in. You can use the <object> tag to specify where in your HTML document layout you want a Flash movie (.swf file) to appear.

Warning

The implementation of the <object> tag discussed in this section is oriented to Internet Explorer for Windows implementation. I strongly encourage you to use the SWFObject JavaScript library discussed later in this chapter for the best method of Flash content integration with HTML content.

Note

Flash Player 6 introduced a Stage class that enables you to control or override many of the same properties that the Player HTML tags specify. For more details on the Stage class, refer to the Flash ActionScript Bible series (Wiley).

A. <object
B.      classid="clsid: clsid:d27cdb6e-ae6d-11cf-96b8- 
Using the <object> tag
444553540000" C. codebase="http://download.macromedia.com/pub/
Using the <object> tag
shockwave/cabs/flash/swflash.cab#version=10,0,0,0" D. width="550" height="400" E. id="home" F. align="middle"> G. <param name="allowScriptAccess" value="sameDomain" /> H. <param name="allowFullScreen" value="false" /> I. <param name="movie" value="home.swf" /> J. <param name="play" value="false" /> K. <param name="loop" value="false" /> L. <param name="menu" value="false" /> M. <param name="quality" value="high" /> N. <param name="scale" value="noborder" /> O. <param name="salign" value="LT" /> P. <param name="wmode" value="transparent" /> Q. <param name="devicefont value="true" /> R. <param name="bgcolor" value="#FFFFFF" />
S.      <param name="flashvars" value="title=My%20Movie" />
T.      <param name="base" value="." />
U.      </object>

Note

Flash CS5's HTML templates use XHTML-compliant code. Notice that all the tags use lowercase, and that all <param> tags end with a />.

  1. <object: This is the opening tag containing the ID code and locations of the ActiveX control for the Flash Player. Note that this opening tag includes the attributes lettered B through F.

  2. classid: This lengthy string is the unique ActiveX identification code. If you are inserting the <object> tag by hand in a text editor, make sure that you copy this ID string exactly.

  3. codebase: Like the codebase attribute of a Java <applet> tag, this attribute of the <object> tag specifies the location of the ActiveX control installer file (.cab) as a URL. Notice that the #version=10,0,0,0 portion of the URL indicates that the Flash Player version 10 should be used. You can also specify specific minor releases, such as #version=6,0,65,0, which would require Flash Player 6.0 r65 ActiveX control or later. If the visitor doesn't have the ActiveX control already installed, Internet Explorer automatically downloads the control from this URL.

    Tip

    If you want to make a secure Web page with Flash content, make sure that the codebase URL uses https:// rather than http://.

  4. width and height: These attributes control the actual width and height, respectively, of the Flash movie as it appears on the Web page. If no unit of measurement is specified, these values are in pixels. If the % character is added to the end of each value, the attribute adjusts the Flash movie to the corresponding percent of the browser window. For example, if 100 percent was the value for both width and height, the Flash movie fills the entire browser, except for the browser gutter. See Colin Moock's tutorial at the Web archive for this book to learn how to minimize this gutter thickness.

  5. id: This attribute of the <object> tag assigns a JavaScript/VBScript identifier to the Flash movie so that it can be controlled by DHTML JavaScript/VBScript functions. By default, this attribute's value is the name of the actual .swf file, without the .swf extension. Each element on a DHTML page should have a unique id or name attribute. I discuss the name attribute in the next section.

  6. align: This attribute of the <object> tag determines how the Flash movie aligns on the HTML document. The acceptable values for this attribute are left, right, top, bottom, or middle. As with <img> tags in HTML, the align attribute gives very loose layout control. It's likely that you'll want to rely on other HTML tags and cascading style sheets (CSS) to position a Flash movie with other HTML elements.

  7. <param name="allowScriptAccess" value="sameDomain" />: This is the first set of <param> subtags within the <object></object> tags. Each parameter tag has a unique name= setting, not to be confused with JavaScript names or ids. allowScriptAccess controls how the Flash movie can access JavaScript or VBScript functions contained within the HTML document. A Flash movie can try to invoke a JavaScript or VBScript function by using an ActionScript fscommand() or getURL() line of code. There are three values supported: always, never, and sameDomain. The value always enables the Flash movie to access scripts on the page, and never prohibits the Flash movie from accessing scripts. The value sameDomain, which is the default value, enables a Flash movie to access scripts on the page only if the Flash movie resides on the same domain as the HTML page containing the movie. The allowScriptAccess attribute is supported by Flash Player 6 r40 and later.

  8. <param name="allowFullScreen" value="false" />: This parameter specifies if the Flash movie can utilize full screen mode when playing in a Web browser window. If set to false, a Flash movie cannot play outside of the browser in full screen mode. If set to true, a Flash movie's stage can take over the entire desktop screen area and play outside of a Web browser window. You must script full screen capability within your Flash movie to use this feature. The ActionScript 3.0 version of the FLVPlayback component in Flash CS5, for example, includes a full screen feature. The allowFullScreen attribute is supported only by Flash Player 9 r28 or later.

  9. <param name="movie" value="home.swf" />: This parameter determines which Flash movie file (.swf) is loaded into the document. The value attribute specifies the filename of the Flash movie, as a relative or absolute URL. Note that you can pass Flash variables to the movie directly by specifying them after the filename. For example, home.swf?firstName=Jeremy passes a variable named firstName with a string value of Jeremy to the root timeline (that is, _level0). You can use the newer flashvars (item S) HTML attribute to do this type of data transfer as well.

    Note

    In ActionScript 3.0, variables declared with the flashvars attribute are accessed through the parameters property of the LoaderInfo class on the root instance.

  10. <param name="play" value="false" />: This optional parameter tells the Flash Player whether it should start playing the Flash movie as it downloads. If value equals false, the Flash movie loads in a "paused" state, just as if a stop() action was placed on the first frame. If the value equals true, the Flash Player starts playing the movie as soon as it starts to stream into the browser. If this tag is omitted, the Flash Player behaves as if play equals true.

    Note

    If you do have a stop() action on the first frame of your movie, setting play to true does not override the stop() action.

  11. <param name="loop" value="false" />: This optional setting tells the Flash Player whether the Main Timeline should repeat when the playhead reaches the last frame. If value equals false, the playhead does not loop. If value equals true, the playhead loops. If this parameter tag is omitted, the Flash Player by default loops playback of the Main Timeline.

    Note

    If you have a stop() action on the last frame of the Main Timeline, the Flash movie does not loop, regardless of the HTML loop value.

  12. <param name="menu" value="false" />: This setting controls the display of the Flash Player contextual menu that can be invoked by right-clicking (Windows) or Control+clicking (Mac) the Flash movie in the Web browser. If you set this option to false, the menu displays the options shown in Figure 19.1. If you set this option to true, all the options are available to the end user, as shown in Figure 19.2. Also, the player's Settings option is available in both modes of the menu.

    The Flash Player menu with control options disabled

    Figure 19.1. The Flash Player menu with control options disabled

    Note

    The default Play, Stop, and Rewind options that were available in Flash Player 6 and earlier are no longer available in Flash Player 7 or later.

    Note

    If you have installed the Debugger version of Flash Player 10, the contextual menu displays a Debugger option in both modes of the menu attribute (true and false). Figure 19.2 shows the Debugger option. For more information on using the Debugger, read Adobe's DevNet article at www.adobe.com/devnet/flash/articles/as3_debugger.html.

    Note

    Flash Player 7 and later supports additional items that you can script into the contextual menu, using the ContextMenu class. For more detailed information on the usage of this class, refer to the Flash CS5 Help panel and the Flash ActionScript Bible series (Wiley).

    The Flash Player menu with control options enabled

    Figure 19.2. The Flash Player menu with control options enabled

  13. <param name="quality" value="high" />: This parameter controls how the Flash movie's artwork renders within the browser window. value can be low, autolow, autohigh, high, or best. Most Flash movies on the Web use the high value because this setting forces the Flash Player to render the movie elements anti-aliased. For a full description of each of the quality settings, refer to Chapter 20, "Publishing Flash Movies."

  14. <param name="scale" value="noborder" />: This optional parameter controls how the Flash movie scales in the window defined by the width and height attributes of the opening <object> tag. Its value can be showall, noborder, exactfit, or noscale. If this entire subtag is omitted, the Flash Player treats the movie as if the showall default setting was specified. The showall setting fits the Flash movie within the boundaries of the width and height dimensions without any distortion to the original aspect ratio of the Flash movie. Again, refer to Chapter 18 for a complete description of the scale settings and how they work within the dimensions of a Flash movie.

  15. <param name="salign" value="lt" />: This parameter controls the alignment of the Flash movie within the space allocated to the viewing area of the movie in the browser window. For example, if you size your Flash movie to use 100 percent of the width and height of the browser window, a value of lt aligns the Flash movie to the left and top of the browser window. The acceptable values for this parameter are shown in the following list. For more information, refer to our coverage in Chapter 18, "Publishing Flash Movies."

    • l : left edge, centered vertically

    • r : right edge, centered vertically

    • t : top edge, centered horizontally

    • b : bottom edge, centered horizontally

    • lt : left and top edges

    • rt : right and top edges

    • lb : left and bottom edges

    • rb : right and bottom edges

  16. <param name="wmode" value="transparent" />: This Player option works with all versions of the Flash Player if you are using Internet Explorer (version 3 or later) for Windows, or with Flash Player 6 r65 or later on Internet Explorer, Netscape, and most Mozilla-based browsers. If you are targeting an audience that uses these browsers, you can control how the Flash movie's background color appears on top of the HTML or DHTML elements on the Web page. There are three acceptable values:

    • window: This value is the default appearance of movies playing in the Flash Player on Web pages. With this value, movies play within the area specified by the width and height attributes (discussed in item D), and the background color of the Flash movie's stage (as defined by Document Properties, or item Q, later in this section) appears.

    • opaque: This value provides the same visual appearance of the movie's stage as window does. However, if you want to animate other DHTML objects in front of or behind a layer containing the Flash movie, it is recommended that you use the opaque value.

    • transparent: This value enables the stage of the Flash movie to act like an alpha channel. When enabled, the Flash movie appears to float on the HTML page, without any background color to reveal the corners of the Flash movie's stage. Again, although this feature is somewhat extraordinary, it functions only with specific browsers and later versions of the Flash Player plug-in. Also, because the browser must anti-alias the Flash artwork on top of other HTML elements, playback of Flash animations may suffer.

  17. <param name="devicefont" value="true" />: This feature controls how Flash text appears in the browser window and works only on the Windows operating system. Like the device fonts with the Flash authoring environment (_sans, _serif, and _typewriter), this option can display any and all embedded text to system fonts such as Times and Arial. To do this, set value to true. To disable device font rendering in this fashion, set value to false. If this tag is omitted from the HTML, the value defaults to false. Finally, the rules of Flash device fonts apply to system device fonts as well. For example, device or system fonts cannot be masked, rotated, or manipulated with the Transform panel or the Property inspector.

    Note

    This seldom-used setting does not work predictably from use to use. In our tests, I could not get devicefont to work consistently from movie to movie, nor could I propose any reasonable use for it. It's likely that this is a legacy setting, meaning that it was made available for machines that had slow video or computing performance when the Flash Player was first introduced to the market.

  18. <param name="bgcolor" value="#FFFFFF" />: This parameter name, bgcolor, controls the background color of the Flash movie. If you published an HTML document via the Publish command, the value is automatically set to the background color specified by the Modify

    The Flash Player menu with control options enabled
  19. <param name="flashvars" value="title=My%20Flash%Movie" />: This Flash Player 6 and later attribute enables you to declare variables within the Flash movie when it loads into the Web browser. flashvars stands for "Flash Variables." This feature enables you to circumvent the browser URL length limitation for declaring variables in the Flash movie's filename, as I discuss in item I of this list. For example, you can use client-side (for example, JavaScript) or server-side (for example, ColdFusion, ASP, PHP) scripting to dynamically write the value for this tag in your HTML, passing information from databases into the Flash movie at load time.

    Tip

    If you use Flash Remoting services with your Flash movie, be sure to declare the gatewayUrl variable in flashvars. The gatewayUrl variable specifies the location of the Flash Remoting gateway, such as <param name="flashvars" value="gatewayUrl= http://mydomain.com/flashservices/gateway" />.

  20. <param name="base" value="." />: This attribute tells the Flash movie how to interpret any relative paths used with ActionScript. The default value is ".", which means that Flash resolves any relative paths within ActionScript to the same directory that the Flash movie resides in. For example, if base is set to ".", the following action in ActionScript 3.0 looks for an HTML document named form.html in the same directory as the Flash movie file (.swf):

    navigateToURL(new URLRequest("form.html"));

    You can use dot notation with the base attribute, such as "../", or specify a fully qualified domain name, such as "http://www.myserver.com/section_1", to let the Flash movie know that all relative paths should be resolved from that starting point.

    Note

    You can read Macromedia's tech notes about the base attribute by perusing the links in the "Flash and HTML Tags" category at www.flashsupport.com/links.

    Warning

    In our tests, I only saw the base attribute recognized by getURL() or navigateToURL() actions. Other actions that use URLs, such as loadMovie(), LoadVars, XML, and NetStream, did not use the base attribute to resolve relative URLs. If you keep your Flash movie files (.swf) in a separate folder from assets that need to be loaded into the Flash movies, you should pass the starting path into the Flash movie with flashvars (see item S in this list) and append that value to all of your relative paths in ActionScript. Also, if you use dot notation with the base attribute, such as "../", the path is oddly interpreted relative to the HTML document, not the Flash movie.

  21. </object>: This is the closing tag for the starting <object> tag. As I show you later in this chapter, you can put other HTML tags between the last <param> tag and the closing </object> tag for non-ActiveX-enabled browsers, such as Netscape or Apple Safari. Because Internet Explorer for Windows is the primary browser that currently implements <object> tags, most browsers simply skip the <object> tag (as well as its <param> tags) and read only the tags between the last <param> and </object> tags.

Tip

I recommend that you consistently apply quotes around names and values, such as <param name="bgcolor" value="#FFFFFF" />. This syntax is especially important for the flashvars attribute.

Using the <embed> tag

Netscape and Mozilla-based browsers use the <embed> tag to display nonbrowser, native file formats that require a plug-in, such as Adobe Flash Player and Shockwave Director or Apple QuickTime. Following is a sample listing of attributes and values for the <embed> tag. Again, attributes with an asterisk are generally optional for most Flash movie playback.

Note

The <object> tag can be used with most Mozilla-based browsers, but the implementation is somewhat different than that of Internet Explorer for Windows. You learn more about using the <object> tag for Mozilla-based browsers in our coverage of SWFObject later in this chapter.

A. <embed
B.         src="home.swf"
C.         play="false"
D.         loop="false"
E.         quality="high"
F.         scale="noborder"
G.         salign="lt"
H.         wmode="transparent"
I.         devicefont="true"
J.         bgcolor="#FFFFFF"
K.         width="550" height="400"
L.         swLiveConnect="false"
M.         name="home"
N.         id="home"
0.         align="middle"
P.         allowScriptAccess="sameDomain"
Q.         allowFullScreen="false"
R.         flashvars="name=Lucian"
S.         type="application/x-shockwave-flash"
T.         base="."
U.         pluginspage="http://www.macromedia.com/go/ 
Using the <embed> tag
getflashplayer"> V. </embed>
  1. <embed: This is the opening <embed> tag. Note that lines B through T are attributes of the opening <embed> tag, which is why you don't see the > character at the end of line A.

  2. src: This stands for source, and it indicates the filename of the Flash movie. This attribute of <embed> works exactly like the movie parameter of the <object> tag.

  3. play: This attribute behaves in the same manner as the play parameter of the <object> tag. If you omit this attribute in your HTML, the Flash Player assumes that it should automatically play the Flash movie.

  4. loop: This attribute controls the same behavior as the loop parameter of the <object> tag. If you omit this attribute in your HTML, the Flash Player automatically loops playback of the movie's Main Timeline.

  5. quality: This attribute controls how the Flash movie's artwork appears in the browser window. Like the equivalent quality parameter of the <object> tag, its value can be low, autolow, autohigh, high, or best.

  6. scale: This attribute of <embed> controls how the Flash movie fits within the browser window and/or the dimensions specified by width and height (item K). Its value can be showall (default if attribute is omitted), noborder, exactfit, or noscale.

  7. salign: This attribute controls the internal alignment of the Flash movie within the viewing area of the movie's dimensions. See the description for the salign parameter of the <object> tag for more information.

  8. wmode: This attribute controls the opacity of the Flash movie's background color and works only with specific browser and Flash Player version combinations. See the wmode parameter description in the <object> tag for more details.

  9. devicefont: This attribute controls the appearance of any text within a Flash movie and functions correctly only on the Windows operating system. See the description for devicefont in the <object> tag section.

  10. bgcolor: This setting controls the Flash movie's background color. Again, this attribute behaves identically to the equivalent <param> subtag of the <object> tag. See that tag's description in the preceding section.

  11. width and height: These attributes control the dimensions of the Flash movie as it appears on the Web page. Refer to the width and height descriptions of the <object> tag for more information.

  12. swLiveConnect: This is one attribute that you won't find in the <object> tag. This unique tag enables Netscape's LiveConnect feature, which enables plug-ins and Java applets to communicate with JavaScript. By default, this attribute is set to false. If it is enabled (the attribute is set to true), the Web page may experience a short delay during loading. The latest versions of Netscape don't start the Java engine during a browsing session until a Web page containing a Java applet (or a Java-enabled plug-in such as the Flash Player) is loaded. Unless you use fscommand() actions in your Flash movies, it's best to omit this attribute or set its value to false.

  13. name: This attribute works in tandem with the swLiveConnect attribute, enabling the Flash movie to be identified in JavaScript. The value given to the name attribute is the Flash movie object name that can be used within your JavaScript programming.

  14. id: This attribute is also used for JavaScript functionality. It's uncertain whether this value is necessary if the name attribute exists, but Flash MX 2004's Flash with FSCommand HTML template (in the Publish Settings dialog box) includes both the name and id attributes. The id attribute should use the same value as the name attribute.

  15. align: This attribute behaves exactly the same as the align parameter for the <object>. See its description in the preceding section for more information.

  16. allowScriptAccess: This attribute controls how the Flash movie can access JavaScript from getURL() and fscommand() actions. See the description of allowScriptAccess in the <object> tag coverage earlier in this chapter.

  17. allowFullScreen: This attribute determines the full screen capability of a Flash movie running in Flash Player 9 r28 or later. See the description of allowFullScreen in the <object> tag coverage earlier in this chapter.

  18. flashvars: This attribute assigns variables to the Main Timeline of the Flash movie at runtime. See the description of flashvars in the <object> tag coverage earlier in this chapter.

  19. type="application/x-shockwave-flash": This attribute tells the browser what MIME (Multipurpose Internet Mail Extension) content-type the embedded file is. Each file type (TIF, JPEG, GIF, PDF, and so on) has a unique MIME content-type header, describing what its content is. For Flash movies, the content-type is application/x-shockwave-flash. Any program (or operating system) that uses files over the Internet handles MIME content-types according to a reference chart that links each MIME content-type to its appropriate parent application or plug-in. Without this attribute, the browser may not understand what type of file the Flash movie is. As a result, it may display the broken plug-in icon when the Flash movie downloads to the browser.

  20. base=".": This attribute tells the Flash movie how to resolve relative paths used in the movie's ActionScript code. See the description of base in the <object> tag coverage earlier in this chapter.

  21. pluginspage: Literally "plug-in's page," this attribute tells the browser where to go to find the appropriate plug-in installer if it doesn't have the Flash plug-in already installed. This is not equivalent to a JavaScript-enabled auto installer or detection page. It simply redirects the browser to the URL of the Web page where the appropriate software can be downloaded.

  22. </embed>: This is the closing tag for the original <embed> tag in line A. Some older or text-based browsers such as Lynx are incapable of displaying <embed> tags. You can insert alternate HTML (such as a static or animated GIF image with the <img> tag) between the <embed> </embed> tags for these browsers. Some browsers may require that you insert these alternate tags between a <noembed></noembed> set of tags within or after the <embed></embed> tags.

Detecting the Flash Player

What good is an awesome Flash experience if no one can see your Flash movies? Because most Flash content is viewed with a Web browser, it's extremely important to make sure that your HTML pages check for the existence of the Flash Player plug-in before you start pushing Flash content to the browser. There are a variety of ways to check for the Flash Player, and this section provides an overview of the available methods.

Plug-in versus ActiveX: Forcing content without a check

The Flash Player is available for Web browsers in two forms: the Flash Player plug-in (as a Netscape-compatible, or Mozilla-compatible, plug-in) and the Flash Player ActiveX control (for use only with Microsoft Internet Explorer on Windows 98/ME/2000/XP/Vista/7).

If you directly insert a Flash movie into a Web page with the <embed> tag (for Mozilla browsers), one of two scenarios happens:

  • The browser has the Flash Player plug-in and loads the Flash movie.

  • The browser does not have the Flash Player plug-in and displays a broken plug-in icon.

If the second scenario occurs and the pluginspage attribute of the <embed> tag is defined, the user can click the broken plug-in icon and go to the Adobe site to download the Flash Player plug-in. If the pluginspage attribute is not specified, clicking the broken plug-in icon takes you to a generic plug-in page provided by the browser vendor.

If you insert a Flash movie into an HTML document with the <object> tag (for Internet Explorer on Windows only), one of two scenarios happens:

  • The browser has the Flash Player ActiveX control and loads the Flash movie.

  • The browser does not have the Flash Player ActiveX control and auto-downloads and installs the ActiveX control file from the Adobe site.

Note

Newer versions of Windows XP (that is, with Service Pack 2 or SP2 installed) will likely get an additional warning represented as a strip across the top of the Web page attempting to initiate the installation of a new ActiveX control. The user must also click this strip and accept the download of the ActiveX control.

The ActiveX control auto-downloads and installs only if the classid and codebase attributes of the Flash movie's <object> tag are correctly specified. Depending on the user's security settings, the user needs to grant permission to a Security Warning dialog box to commence the download and install process.

Although using the <object> and <embed> tags by themselves is by far the simplest method for integrating Flash content into a Web page, it's not the most user-friendly method of ensuring that the majority of your Web visitors can view the Flash content. Flash CS5 uses an updated JavaScript detection mechanism, replacing the older JavaScript approach used in Flash CS3.

Note

Since Flash Player 4 was released, many seasoned Flash developers have used small Flash movies known as sniffers to detect the presence of the Flash Player in a user's Web browser. Sniffers are virtually hidden from the visitor to a Web site, and they direct an entry HTML page to a new location (using a getURL() action) where the real Flash content (or site) exists. If the Player is not installed, the sniffer movie cannot play and directs the HTML page to a new location. If this happens, a special <meta> tag in the <head> of the HTML document directs the browser location to a screen that informs the visitor to download the plug-in or ActiveX control. However, page redirection mechanisms are not ideal for search engine optimization — I recommend using SWFObject as discussed later in this chapter.

Detecting the Flash Player with Flash CS5

In Flash CS5, Adobe has made the process of using a sniffer methodology incredibly simple. In the following steps, you learn how to use the Detect Flash Version feature to properly direct a user to Flash Player 6 r65 content.

Note

You can check for Flash Player 4 or later with the Detect Flash Version feature. For demonstration purposes, I chose Flash Player 6 r65 because Flash MX 2004 introduced a new optimization feature for .swf files generated for this version (or later) of Flash Player 6.

Warning

If you used the Detect Flash Version in older versions of Flash such as Flash MX 2004, be sure to review this section. The feature no longer uses three HTML pages for the detection process. Everything from the detection to the content display to the alternate content display occurs on one HTML page.

  1. Create a new Flash document by choosing File

    Detecting the Flash Player with Flash CS5
  2. Save the new Flash document as detection_test.fla.

  3. Add some placeholder text to the Stage by using the Text tool. Because this example is checking for Flash Player 9 r28, you can type This is Flash Player 9 r28 content.

  4. Choose File

    Detecting the Flash Player with Flash CS5
  5. To keep the new version settings in a separate profile, click the Create New Profile (+) button at the top of the Publish Settings dialog box. Name the profile FP9 r28 Detection, as shown in Figure 19.3. Click OK to close the dialog box, but leave the Publish Settings dialog box open.

  6. Click the Flash tab. In the Version menu, choose Flash Player 9. In the ActionScript version menu, choose ActionScript 3.0 if not already selected. See Figure 19.4 for a review of these settings.

    The Create New Profile dialog box, showing the new profile name.

    Figure 19.3. The Create New Profile dialog box, showing the new profile name.

    The Flash Player 9 settings in the Flash tab.

    Figure 19.4. The Flash Player 9 settings in the Flash tab.

  7. Click the HTML tab of the Publish Settings dialog box and select the Detect Flash Version check box. The two editable text fields to the right of the Version label should now be enabled. The major version of the Flash Player is fixed to the Player version you chose in the Flash tab. The first of the two editable fields represents a Minor Revision value; to date, Adobe hasn't released any minor revisions of the Flash Player, but this feature is enabled just in case Adobe does release any minor revision during the life cycle of the Flash CS5 authoring tool. The second field represents the Incremental Revision value. Since Flash Player 4, Adobe has released several incremental revisions of the Flash Player for each player cycle.

    Note

    To get a sense of how many incremental revisions of Flash Player 7 were released, see the "Flash Player Release Notes" category at www.flashsupport.com/links.

  8. Type 28 in the second field, as shown in Figure 19.5. If you wanted to check for a different incremental version of Flash Player 9, you could enter that value instead. Click OK to close the dialog box, and go back to the HTML tab of the Publish Settings dialog box.

    The Publish Settings dialog box

    Figure 19.5. The Publish Settings dialog box

  9. In the Publish Settings dialog box, click the Publish button. Flash CS5 generates all the necessary JavaScript within the published HTML document to properly detect the Flash Player version. Click OK to close the Publish Settings dialog box.

  10. On your desktop, navigate to the folder where you saved your original .fla file. If you created the sample document in Step 1, you want to find the location of detection_test.fla. In this location, you will see the HTML file created for the detection process.

  11. In your own Web browser, load the detection_test.htmlpage. If your browser has Flash Player 9 r28 or later, the browser should display your detection_test.swf movie. This process works because the detection_test.html page uses JavaScript to check the installed Flash Player version, if one exists. If you open the HTML document in a text editor such as Adobe Dreamweaver CS5, you'll see that lines 286–291 declare the version numbers you entered in the HTML tab of the Publish Settings dialog box. The JavaScript code compares these values to the version of the Flash Player that loaded the movie. If the Flash Player matches (or exceeds) the version requirements, the Flash content tags (<object> and <embed>) are written to the HTML page with JavaScript. Otherwise, the alternate content specified on line 330 in the JavaScript code is loaded into the browser window.

    Note

    Adobe provides generic alternate content that you should replace with your own preferred HTML tags indicating what you want to the user to do if the version of the Flash Player required is not installed.

  12. To accurately test your pages over an Internet connection, upload all the files (except the .fla file) to your Web server and load the detection_test.html document from the Web server URL to redo the test.

Note

You can find all these files created for this detection example in the ch19/flashCS5_detection folder of this book's CD-ROM. The JavaScript in the detection_test_fCS5b.html version of the document contains additional alternate content that is specified in an alternate.js file, also included on the CD-ROM. If you want to find the latest "Get Flash Player" graphics to use in your Web pages, go to www.adobe.com/macromedia/style_guide/buttons.

If you want to test the detection mechanism with an older version of the Flash Player, I recommend that you use an older Flash Player installer with a Mozilla-compatible browser. The process of uninstalling an ActiveX control used by Internet Explorer is much more difficult to do.

Note

You can find just about every past version of the Flash Player at www.adobe.com/cfusion/knowledgebase/index.cfm?id=tn_14266 for testing purposes. As mentioned previously, I recommend that you install the older versions with a Mozilla-compatible browser. If you are using Mac OS X, the first Flash Player released for Mac OS X was version 5.

You can set up your Mozilla-compatible browser's plug-ins folder to accommodate multiple versions of the Flash Player plug-in. When you installed Flash CS5, the latest release of Flash Player 9 should have automatically been installed to your Mozilla-based browser's Plugins (or plugins) folder. The plug-in file, named NPSWF32.dll, can be moved outside of the Plugins folder, into a new parent folder that you create. For the following example, we'll use Mozilla Firefox as our test browser.

Note

Mozilla Firefox is a free Web browser that you can download at www.mozilla.org/products/firefox/. Firefox has quickly become the preferred cross-platform browser of many Web developers.

I prefer to create a _Flash Players folder in the C:Program FilesMozilla FireFox folder, and put each Flash Player version plug-in file into its own folder, as shown in Figure 19.6.

Warning

Regardless of the Flash Player version you install, all Flash Player plug-in files for Mozilla-compatible browsers have the same name on Windows: NPSWF32.dll. For this reason, you must isolate multiple installations of the Flash Player into their own folder.

A sample Flash Players folder structure for use with Mozilla Firefox on Windows

Figure 19.6. A sample Flash Players folder structure for use with Mozilla Firefox on Windows

You can do the same procedure on Mac OS X, where all browsers share the same plug-in folders. That's right! Mozilla, Firefox, Internet Explorer, and Apple Safari all refer to the same plug-ins folder. On your boot disk, such as Macintosh HD, browse to the LibraryInternet Plug-Ins folder. In this location, you find the Shockwave Flash NP-PPC plug-in file. As Figure 19.7 shows, you can create a LibraryInternet Plug-Ins (DISABLED) folder to store other versions of this plug-in file.

Warning

On Mac OS X, you may need to re-create the same plug-in structure with the Users[Your User Name]LibraryInternet Plug-Ins folder. Or, you may just want to remove any Flash Player plug-in files within this folder. Mac OS X should then default to the main LibraryInternet Plug-Ins folder.

This process takes some time because you have to download and run each installer from the URL I mentioned in the earlier Web Resource note, and move the NPSWF32.dll file from the Plugins folder to its own folder in the Flash Players folder. When you're done, however, you'll have an efficient system for checking your content against older versions of the Flash Player. Simply move the current NPSWF32.dll file into its appropriate _Flash Players folder, and move the desired test version from its Flash Players folder into the Plugins folder.

A sample Flash Players folder structure for use with Mozilla Firefox or Apple Safari on Mac OS X

Figure 19.7. A sample Flash Players folder structure for use with Mozilla Firefox or Apple Safari on Mac OS X

Tip

If you use Firefox 3.0, you're in luck. Alessandro Crugnola has built Flash Switcher, a free Flash Player plug-in utility that includes past versions of the Flash Player and swaps your installed version of the player with a convenient menu built right into the browser window! For more information, see www.sephiroth.it/firefox/flash_switcher/.

Detecting the Flash Player with SWFObject

Although the Adobe Flash CS5 detection features work wonderfully, you should know about a popular and widely used JavaScript library, SWFObject. This JavaScript code, created by Geoff Stearns, can be downloaded at code.google.com/p/swfobject/. I've included the latest version, 2.2, in the ch19/swfobject/swfobject_2-2 folder on this book's CD-ROM. In this section, you learn how to use SWFObject with Flash content.

Note

SWFObject 2.0 and later supports two methods of publishing Flash content: static and dynamic. In this walk-through, I use the static method, which is more Web standards–compliant. For more information, visit code.google.com/p/swfobject/wiki/documentation.

Reviewing the content

We've included a Flash movie named trafficLightGreen.swf in the ch19/swfobject folder. This file displays a vector graphic of a flashing green traffic light, as shown in Figure 19.8. The SWFObject code displays this movie only if Flash Player 9 r28 is installed, which is required for full screen capability.

A sample Flash movie

Figure 19.8. A sample Flash movie

An alternative non-Flash piece of content has also been provided in the ch19/swfobject folder: trafficLightRed.gif, as shown in Figure 19.9.

The HTML document displays this GIF file in the following cases:

  • Flash Player 9 r28 or later is not installed.

  • JavaScript has been disabled by the user in the Web browser's preferences.

A sample alternate graphic

Figure 19.9. A sample alternate graphic

Copy both the SWF and GIF files from the CD-ROM to a preferred location on your computer. Be sure to save the HTML file discussed in the next section to the same location.

Creating the HTML document

In this section, you learn how to build an HTML file that uses the SWFObject library to determine which piece of content, the Flash movie or the GIF graphic, to display in the Web browser.

Warning

In the code samples shown in this section and throughout the book, do not type the

Creating the HTML document
  1. In Adobe Dreamweaver CS5, create a new HTML file by choosing File

    Creating the HTML document
  2. Save the HTML file as swfobject_sample.html.

  3. Copy the swfobject.jsand expressInstall.swf files from the ch19/swfobject/swfobject_2_1 folder to the same location as your HTML file saved in Step 2. The swfobject.js JavaScript file contains the Flash Player detection code, and the expressInstall.swf file is a pre-built Flash movie (swf file) that automatically downloads the latest version of the Flash Player if the required Flash Player version is not available. Note that the expressInstall.swf file requires Flash Player 6 r65 or later to be installed to initiate the automated plug-in download-and-install process.

    The New Document dialog box in Adobe Dreamweaver CS5.

    Figure 19.10. The New Document dialog box in Adobe Dreamweaver CS5.

  4. After the closing </title>tag and before the closing </head>tag, insert the following code to load the SWFObject code into the HTML document:

    <script type="text/javascript" src="swfobject.js"></script>
  5. Between the <body></body> tags, add the code shown in Listing 19.2. The <div> container specifies both the Flash movie (.swf file) that you want to appear on the page as well as the alternate content that you want to appear if the required version of the Flash Player is unavailable. The alternate content is also indexed by search engines.

  6. Go back up to the <head>section of your HTML document and add the following code. This code creates a new SWFObject instance in JavaScript. If the required Flash Player version is installed (version 9 r28), the <div> content displays the Flash movie specified in the <object> tags. Review the code comments to see the parameters required for a new SWFObject instance.

    <script type="text/javascript">
       swfobject.registerObject("flashContent", "9.0.28", 
    The New Document dialog box in Adobe Dreamweaver CS5.
    "expressInstall.swf"); </script>
  7. Save the HTML file and test the file in a Web browser. If the browser has Flash Player 9 r28 installed, you should see the green traffic light animation. If the browser has an earlier version of the Flash Player or does not have any version of Flash Player installed, the red traffic light graphic appears.

Example 19.1. The HTML Starter Code

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"  
The HTML Starter Code
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>SWFObject Detection</title> </head> <body> </body> </html>

Example 19.2. The Flash Movie and Alternate Content

<div>
   <object id="flashContent" classid="clsid:D27CDB6E-AE6D-11cf-
The Flash Movie and Alternate Content
96B8-444553540000" width="105" height="185"> <param name="movie" value="trafficLightGreen.swf" /> <!--[if !IE]>--> <object type="application/x-shockwave-flash"
The Flash Movie and Alternate Content
data="trafficLightGreen.swf" width="105" height="185"> <!--<![endif]--> <img src="trafficLightRed.gif" width="105" height="185"
The Flash Movie and Alternate Content
align="left"/> <p style="font-family:Verdana, Arial, Helvetica,
The Flash Movie and Alternate Content
sans-serif; position: relative; top: 50px; width:
The Flash Movie and Alternate Content
300px;">Please download the <a
The Flash Movie and Alternate Content
href="http://www.adobe.com/go/getflashplayer">latest
The Flash Movie and Alternate Content
Flash Player</a> for the best experience.</p> <!--[if !IE]>--> </object> <!--<![endif]--> </object> </div>

Note

You can find the finished HTML code in the ch19/swfobject folder on this book's CD-ROM.

Using Flash Movies with JavaScript and DHTML

The ActionScripting features of Flash Player 8 or later have increased the range of interactive and dynamic possibilities for Flash movies on the Internet. 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 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 ExternalInterface API (application programming interface) introduced with Flash Player 8.

Tip

The ExternalInterface API is part of the flash.external package in ActionScript 2.0 and 3.0, and is available in Flash Player 8 or later (AS2) and Flash Player 9 and later (AS3). 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 ExternalInterface API actions, which, when used in Flash movies on Web pages, are supported by the following browsers:

  • Internet Explorer 4.0 and later for Windows 98/ME/2000/XP/Vista/7

  • Mozilla 1.7.5 and later

  • Mozilla Firefox 1.0 and later

  • Opera 9.0 and later

  • Apple Safari 1.3 and later

The 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, read Chapter 15, "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, I don't explain how JavaScript syntax or functions work.

Understanding how Flash movies work with JavaScript

As I mention earlier, Flash Player has a 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, 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. I 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 CS5 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 does not receive the events from the Flash movie.

Note

This edition of the Flash Bible features coverage of the ExternalInterface API in ActionScript 3.0 available in Flash Player 9 or later. If you want 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, I 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 changes 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.

Note

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

Adding ExternalInterface actions to a Flash movie

Open the countdown_starter.fla Flash document from this book's CD-ROM, and use Control

Adding ExternalInterface actions to a Flash movie

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"), invokes 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 changes the HTML background colors.

Here's the process:

  1. Select frame 1 of the actions layer, and open the Actions panel (F9,/Option+F9). In the Script pane, add the following code. Make sure that you are not in Script Assist mode. This code, written in ActionScript 3.0 syntax, imports the ExternalInterface class and creates a changeBgColor() function that accepts one argument named color. 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 need to pass only one argument, color, to the JavaScript host environment.

    import flash.external.ExternalInterface;
    
    function changeBgColor(color:String):void {
       ExternalInterface.call("changeBgColor", color);
    }
  2. On frame 16 of the Main Timeline, add a keyframe on the actions layer. With the keyframe selected, open the Actions panel (F9/Option+F9). 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() passes 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" is 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 20, "Publishing Flash Movies"). In the Formats tab, make sure that only the Flash format check box is selected. Change the Flash filename to countdown.swf. Click OK to close the Publish Settings dialog box. Choose the File

    Adding ExternalInterface actions to a Flash movie

Next, you build the JavaScript code that is added to the HTML file Flash publishes.

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 19.3 is the JavaScript code that defines the custom function changeBgColor that I have created for you.

Make a copy of the countdown_swfobject_starter.html file from the ch21/ExternalInterface folder of this book's CD-ROM. Copy the file to the same location as the countdown.swf file published in the last section. Add the code in Listing 19.3 to the countdown_swfobject_starter.html file.

Note

The line numbers reflect the actual line numbers in the HTML document. Also, remember that the

Enabling JavaScript for Flash movies

Example 19.3. The JavaScript Code to Enable the ExternalInterface Actions

10. <script type="text/javascript" language="javascript">
11. <!--
12. function changeBgColor(hexColor){
13. document.bgColor = hexColor;
14. }
15. //-->
16. </script>

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

  • 10: This HTML tag initializes the JavaScript code.

  • 11: 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.

  • 12: 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.

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

  • 14: This line of code ends the function defined in line 12.

  • 15: This end comment closes the comment started in line 11.

  • 16: The closing </script> tag ends this portion of JavaScript code.

That's it! I also added <center> tags around the <div> tag to center the Flash movie on the HTML page, and I added the allowScriptAccess parameter in the <object> tag, respectively, to "always". After 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.

Note

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

Adding a percentLoaded() method

With Flash Player 8 or later and the ExternalInterface API, JavaScript can also communicate back to the Flash movie. In the Flash movie, you need to define callback handlers by 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/Option+F9). Add the code shown in Listing 19.4 after the first import statement but before the changeBgColor function declaration. Do not type the

    Adding a percentLoaded() method

    The import flash.display.LoaderInfo; statement makes ready the LoaderInfo class necessary for accessing the Flash movie's percent-loaded information. The import flash.sysem.Security; statement makes available the Security class that defines which Web domain can access content with the Flash movie (.swf file).

    The Security.allowDomain("*"); action allows JavaScript to access the Flash movie's methods and properties. Use the "*" value only when testing the file locally. If you intend to upload a live example to your Web server, specify the Web server's domain name.

    The next block of code uses an if statement to check whether the ExternalInterface capabilities are available in the current host environment, such as a Web browser. If ExternalInterface is available, an ActionScript function named getPercentLoaded is exposed to JavaScript with the ExternalInterface.addCallback() method. This method takes two 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), and the Flash function name that is invoked when JavaScript calls the function named as the first argument (getPercentLoaded). The catch statements are invoked only if an error is encountered when the Flash movie tries to access JavaScript with the addCallBack() method. The throw new Error() actions display an error dialog at runtime to alert the user to an error encountered during playback.

    The 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).

  2. Save your Flash document as countdown_complete.fla, and publish your Flash movie.

  3. In a text editor such as Adobe Dreamweaver, Notepad, or TextEdit, open the countdown_swfobject_100.htmldocument from the previous section. Immediately resave this document as countdown_swfobject.html.

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

    <form method="post" action="" name="flashPercent"  
    Adding a percentLoaded() method
    style="display:show"> <input type="text" name="labelField" size="5"
    Adding a percentLoaded() method
    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 19.5 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> 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

    Adding a percentLoaded() method

    Note

    The thisMovie() function code is a slightly modified version of an example taken directly from Adobe'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 that 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_swfobject.html document on this book's CD-ROM. I also recommend that you test the preloading functionality from a remote Web server. If you test the file locally, the Flash Player may throw a security error dialog box.

Example 19.4. The ActionScript Code for the percentLoaded() Function

import flash.external.ExternalInterface;
import flash.display.LoaderInfo;
import flash.system.Security;

Security.allowDomain("*");

if (ExternalInterface.available) {
   try {
      ExternalInterface.addCallback("getPercentLoaded", getPercentLoaded);
   }
   catch (error:SecurityError) {
      throw new Error(error.message);
   }
   catch (error:Error) {
      throw new Error(error.message);
   }
} else {
   throw new Error("ExternalInterface not available for this host 
The ActionScript Code for the percentLoaded() Function
environment."); } function getPercentLoaded():Number { var li:LoaderInfo = this.loaderInfo; var lb:Number = li.bytesLoaded; var tb:Number = li.bytesTotal; return Math.floor((lb/tb)*100); }

Example 19.5. The JavaScript Code for the percentLoaded() Function

function thisMovie(movieName) {
    var isIE = navigator.appName.indexOf("Microsoft") != −1;
    return (isIE)  ?  window[movieName] : 
The JavaScript Code for the percentLoaded() Function
document.getElementById(movieName); }
function percentLoaded(){
              try {

                  var movie = thisMovie("countdown");

                  var pl = movie.getPercentLoaded();

              if(pl >= 100 ){

                        document.flashPercent.labelField.value= "100 %";

                        setTimeout("document.flashPercent.labelField.style.
The JavaScript Code for the percentLoaded() Function
display = 'none'", 2000); clearInterval(checkID); } else { document.flashPercent.labelField.value = pl + " %" ; } } catch(err){ alert("Can't determine percent loaded... Aborting.."); document.flashPercent.labelField.style.display = 'none'; clearInterval(checkID); } } var checkID = setInterval(percentLoaded, 100);

Warning

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

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.

Summary

  • You can customize many Flash movie attributes by adjusting the attributes of the <object> and <embed> tags in an HTML document. Scaling, size, quality, and background color are just a few of the Flash movie properties that can be changed within HTML without altering the original .swf file.

  • Flash CS5 includes a Detect Flash Version feature in the publish settings. This feature automatically creates an HTML document with the appropriate JavaScript and HTML tags to check for a version of the Flash Player that you specify.

  • The SWFObject JavaScript library is a clean and concise method for adding Flash content to HTML pages, as well as detecting and requiring a specific version of the Flash Player.

  • Flash movies can interact with JavaScript and HTML elements on a Web page. This type of interactivity, however, is limited to the 4.0 or later versions of Internet Explorer (on 32-bit Windows versions) and more current versions of Mozilla-compatible browsers.

  • Flash Player 8 or later can receive events and data from JavaScript. For example, JavaScript can query a Flash movie to determine how much of it has downloaded to the browser.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset