MACROMEDIA FLASH  back to
YOUR FIRST FS COMMAND  
Table of Contents
FS Command: A Short Introduction
Support for FS Command
Two Directions of Communication
How Flash Talks to JavaScript
How JavaScript Talks to Flash
Available Flash JavaScript Methods
References

FS Command: A Short Introduction
Note: if you're looking for a javascript/flash gateway, you should also take a look at the "Flash/JavaScript Integration Kit".

For the purposes of this article, "fscommand()" refers mainly to Flash -> JavaScript communication (ie. Flash executing javascript statements in a web browser). However, fscommand's scope is actually broader than that. Without going into too much detail, here's a slightly longer description of fscommand():

"fscommand()" is the name of a function in Flash that provides communication with a flash movie's host application ("application" means anything that can play Flash media, whether natively, eg. the stand-alone Flash player, or with the use of a plug-in, eg. a web browser). For example, a web-based fscommand() might execute a JavaScript function from a Flash button click. (We'll see later that JavaScript can also control the Flash movie playback.) fscommand() can also communicate with Lingo and can send a limited set of built-in commands to the stand-alone Flash player (eg. "Quit", "FullScreen", "AllowScale", "ShowMenu").

Support for FS Command
Okay, let's get back to the topic at hand: using fscommand() on the web. If you intend to develop scripted Flash movies for the web, you need to be aware that not all browsers support fscommand. The specific browsers that support it are:

The specific browsers that don't support fscommand() are:

Unsupported browsers lack the ActiveX (IE) or LiveConnect (Netscape 4 and older) required to communicate between the plugin and the browser. Further, starting with Flash 3.0, if you are developing fscommand Flash content for Netscape 4, you'll need to explicitly enable LiveConnect on every page that hosts a scripted Flash movie (you do not have to enable LiveConnect in Netscape 6.2 and later). To enable LiveConnect, include this attribute in your movie's EMBED tag: swLiveConnect="true". During the enabling process, users will see "Starting Java..." in the Netscape status bar, and will experience a delay (15 seconds is not uncommon) while Java loads.

Two Directions of Communication
So now that you know where fscommand works, you probably want to know how it works. We'll first examine fscommand-based Flash -> Javascript communication. Then we'll take a look at sending information the other way with JavaScript -> Flash methods.

How Flash Talks to JavaScript
(Before we study executing JavaScript code with fscommand, it should be noted that JavaScript may also be executed from getURL() functions exactly like you'd execute javascript from an anchor (<A>) tag. The getURL() approach is actually more widely supported in browsers than fscommand(), not to mention more convenient to code. For more info, see launching a window with a getURL JavaScript call. Now back to fscommand()...)

Flash attempts to send a message to JavaScript whenever an fscommand function executes. When the browser receives an FS Command from Flash, it checks if there's a matching JavaScript function (or VB Script in the case of IE) that can "catch" the command. If there is, it executes that "catcher" function, sending two parameters to it--the values of the "Command" and "Arguments" parameters of the fscommand.

The following diagram illustrates the process, using the example of an fscommand that calls a JavaScript alert. The fscommand's arguments are "call_alert" and "Hello world!", as follows:

fscommand("call_alert", "Hello world!");

The implementation of fscommand in Netscape and IE differs slightly; the diagram shows how the command travels from Flash to JavaScript in both browsers. Below the diagram is the matching Flash sample movie. Take a look at the model and the sample, then I'll get into the details of how to do it.



Sample FS Command Movie: Flash Calls a JavaScript Alert

Let's follow along with the diagram above to see how to implement a Flash to JavaScript FS Command. You can Download a .zip of sample 1 that includes the .fla, .swf, and .html files described in the steps below.
1) Create an FS Command action in Flash.
  • Start a new movie and make a keyframe a few seconds in to the timeline.
  • Bring up the "Frame Actions" panel for that keyframe.
  • From the "Actions" menu under the plus button, add an "FSCommand" action. You'll see "fscommand" added to your list of actions. The parameters panel will contain two text entry fields called "Command" and "Arguments". These two fields are the parameters that will be passed to the JavaScript fscommand-catching function. They can be used for anything, but normally the Command field contains the name of the function you want the to execute, and the Arguments field contains your parameter(s).
  • In the "Command" text field, enter "call_alert".
  • In the "Arguments" text field, enter "Hello world!".

2) Embed your movie in an HTML document.
  • Make an HTML document for your movie, and use the OBJECT and EMBED tags to put your movie on the page. In your OJBECT and EMBED tags, make sure to name your movie using "ID" for the OBJECT tag and "NAME" for the EMBED tag. It is extremely important that you name your movie, and that the names be identical for the OBJECT and EMBED tags. Your FS Command catching function will rely on the movie's name to identify all incoming FS Commands. Also remember to turn Netscape's LiveConnect on using "swLiveConnect='true'". Your page should look something like this (ID, NAME, and swLiveConnect are bolded...don't forget them):
    
    <HTML>
    <HEAD>
    	<TITLE>My First FS Command</TITLE>
    </HEAD>
    
    <BODY>
    
    <OBJECT
    	CLASSID="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
    	WIDTH="100%"
    	HEIGHT="100%"
    	CODEBASE="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab"
    	ID=testmovie>
    	<PARAM NAME="MOVIE" VALUE="mymovie.swf">
    	<PARAM NAME="PLAY" VALUE="false">
    	<PARAM NAME="LOOP" VALUE="false">	
    	<PARAM NAME="QUALITY" VALUE="high">
    	<PARAM NAME="SCALE" VALUE="SHOWALL">
    
    	<EMBED
    		NAME="testmovie"
    		SRC="mymovie.swf"
    		WIDTH="100%"
    		HEIGHT="100%"
    		PLAY="false" 
    		LOOP="false"
    		QUALITY="high"
    		SCALE="SHOWALL" 
    		swLiveConnect="true"
    		PLUGINSPAGE="http://www.macromedia.com/go/flashplayer">
    	</EMBED>
    </OBJECT>
    
    </BODY>
    </HTML>
    
    
3) Add the VB Script for IE.
  • Remember from Stage 2, in the IE version of Diagram 1, above, that IE uses a "teeny bit" of VB Script to catch fscommands and pass them to JavaScript. That's the next thing you need to add. Put the following VB Script code into the HEAD element of your document, making sure to change the word "testmovie" to the name you gave your movie in your OBJECT and EMBED tags:
  • 
    <SCRIPT LANGUAGE="VBScript">
    <!-- 
    // Catch FS Commands in IE, and pass them to the corresponding JavaScript function.
    
    Sub testmovie_FSCommand(ByVal command, ByVal args)
        call testmovie_DoFSCommand(command, args)
    end sub
    
    // -->
    </SCRIPT>
    
    
4) Add the JavaScript function that catches the fscommand.
  • So far you've created a movie that sends an fscommand action to the browser, you've embedded the movie into an HTML page (making sure to name it), and you've created a VB Script that forwards your fscommand to JavaScript if the browser is IE. All you need now is a JavaScript function to catch the fscommand and execute the alert. Put the following JavaScript code into the HEAD element of your document, making sure to change the word "testmovie" to the name you gave your movie in your OBJECT and EMBED tags:
    
    <SCRIPT LANGUAGE="JavaScript"> 
    <!--  
    function testmovie_DoFSCommand(command, args) { 
      if (command == "call_alert") { 
        alert("Here's the Flash message: " + args);
      }
    }
    
    //-->
    </SCRIPT>
    
    
  • A bit of explanation on the JavaScript. The "testmovie_DoFSCommand" function is called any time the movie named "testmovie" sends an fscommand. "DoFSCommand" is a keyword used by Flash to identify functions that should be launched by fscommands. The "testmovie_" prefix indicates the name of the movie calling the command. Hence, a function called "foomovie_DoFSCommand" would be launched when a movie named "foomovie" called an FS Command. The "(command,args)" are the two parameters passed to the function, and carry the values of the "Command" and "Arguments" fields entered in the Flash editor under the fscommand action--in our case "call_alert" and "Hello world!", respectively.
Once your JavaScript function is in place, your FS Command should successfully launch the alert.

You've learned how to send information from Flash to JavaScript. If you want to take a closer look at the files used in the instructions above, remember to download the zip file of sample 1. Next you'll learn how to make JavaScript control Flash.

How JavaScript talks to Flash
JavaScript can send commands to Flash by invoking built-in methods on embedded movie objects. Calling Flash methods works exactly like all calls to built-in methods on JavaScript objects (eg. document.write() or window.close()). From a developer point of view, this direction of communication is one sided--JavaScript methods control a Flash movie entirely in JavaScript, without requiring complementary code in the Flash movie.

I'll go through a single example of controlling a movie by calling a JavaScript Flash method. You can then extrapolate the technique and apply it to any of the Flash methods available (for a complete list of Flash 2.0 and 3.0 methods, see Macromedia's Flash Methods reference document). Take a look at the following sample movie to see an example of Flash controlled by JavaScript.

Sample 2: JavaScript Controls a Flash Movie

Then follow the steps below to see how to it works. For reference, you can download a .zip of the files used in sample 2.


1) Embed your movie in an HTML document.
  • Make an HTML document for your movie, and use the OBJECT and EMBED tags to put your movie on the page. In your OJBECT and EMBED tags, make sure to name your movie using "ID" for the OBJECT tag and "NAME" for the EMBED tag. It is extremely important that you name your movie, and that the names be identical. Your JavaScript function will need to refer the movie it is controlling by name. Also remember to turn Netscape's LiveConnect on using "swLiveConnect='true'". Your page should look something like this (ID, NAME, and swLiveConnect are bolded...don't forget them):
    
    <HTML>
    <HEAD>
    	<TITLE>JavaScript controls Flash</TITLE>
    </HEAD>
    
    <BODY>
    
    <OBJECT
    	CLASSID="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
    	WIDTH="100%"
    	HEIGHT="100%"
    	CODEBASE="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab"
    	ID=testcommand>
    	<PARAM NAME="MOVIE" VALUE="mymovie.swf">
    	<PARAM NAME="PLAY" VALUE="false">
    	<PARAM NAME="LOOP" VALUE="false">	
    	<PARAM NAME="QUALITY" VALUE="high">
    	<PARAM NAME="SCALE" VALUE="SHOWALL">
    
    	<EMBED
    		NAME="testcommand"
    		SRC="mymovie.swf"
    		WIDTH="100%"
    		HEIGHT="100%"
    		PLAY="false" 
    		LOOP="false"
    		QUALITY="high"
    		SCALE="SHOWALL" 
    		swLiveConnect="true"
    		PLUGINSPAGE="http://www.macromedia.com/go/flashplayer/">
    	</EMBED>
    </OBJECT>
    
    </BODY>
    </HTML>
    
    

1) Add a cross-browser function to refer to your movie object.
  • There are two main components to JavaScript Flash calls: 1) the function that calls the Flash method, and 2) the function that returns the appropriate syntax for referring to the Flash movie object, depending on the browser. You didn't think Microsoft and Netscape would implement this in the same way did you? Nope, neither did I. Sigh. So the first bit of script you need simply gives us the right syntax ("document[moviename]" for Netscape and "window[moviename]" for MSIE). You *could* hard code the movie syntax into your method call, but this is nice and portable, and will turn out to be less work. Just drop it into every Flash method-calling script you have and you won't have to worry about compatibility. We'll call the compatibility function when we invoke any Flash method. Here's the code:
    <SCRIPT LANGUAGE="JavaScript"> 
    <!--  
    var movieName = "testcommand";
    
    function thisMovie(movieName) {
      // IE and Netscape refer to the movie object differently.
      // This function returns the appropriate syntax depending on the browser.
      if (navigator.appName.indexOf ("Microsoft") !=-1) {
        return window[movieName]
      } else {
        return document[movieName]
      }
    }
    
  • Set the value of the "movieName" variable to match the name you gave your movie in the EMBED and OBJECT tags.

2) Add the function that calls your Flash method.
  • Once you've dealt with the compatibility issue, calling a Flash method is easy. You refer to the movie object by calling the compatibility script, and passing it the variable which holds the name of your movie (movieName). Then you tack on the name of the Flash method you want to call. Like this:
    function playmovie() {
      thisMovie(movieName).Play();
    }
    	
    //-->
    </SCRIPT> 
    
  • But WAIT! You're not done. What happens if you call a method on a movie that hasn't finished loading yet? Or hasn't even started loading yet? Errors, that's what. So you'll want to check a) that the movie object exists, and b) that it is sufficiently loaded to start your method. The easiest and most reliable way to check those two conditions is to set a JavaScript variable from your Flash movie indicating that the movie has loaded. You can then check that variable before executing any JavaScript methods on the movie. However, you can also check the load status of the movie with JavaScript by evaluating the movie object, and then calling the "PercentLoaded()" method on it. Here's a function that does that:
    // Checks if movie is completely loaded.
    // Returns true if yes, false if no.
    function movieIsLoaded (theMovie) {
      // First make sure the movie's defined.
      if (typeof(theMovie) != "undefined") {
        // If it is, check how much of it is loaded.
        return theMovie.PercentLoaded() == 100;
      } else {
        // If the movie isn't defined, it's not loaded.
        return false;
      }
    }
    
    You can use movieIsLoaded() to check your movie's load status before invoking any methods, like this:
    function playmovie() {
      if (movieIsLoaded(thisMovie(movieName))) {
        thisMovie(movieName).Play();
      }
    }
    

3) Add an event to call your Flash method function.
  • Now that your function to control Flash is ready, all you need to do is call it. For the purposes of testing, I use a form button to call my Flash functions:
    <FORM>
    	<INPUT TYPE="BUTTON" VALUE="Play" ONCLICK="playmovie()">
    </FORM>
    

4) Extrapolate to other methods.
  • You've learned how to call one JavaScript method--"Play()"--on a Flash movie. You can use the same technique to call any JavaScript method that is supported by the Flash player. The methods available with the Flash 2.0 and 3.0 player are listed below. For other methods that are released with new versions of the player, check macromedia's site (see references below). If you're using the Tell Target methods to send JavaScript commands to Flash Movie Clips, make sure to read these notes--those methods are a bit picky...

    Flash 2.0+ Methods
    • Play(): Play the movie.
    • StopPlay(): Stop the movie.
    • IsPlaying(): Check if the movie's playing.
    • GotoFrame (x): Go to frame "x". "x" must be an integer.
    • TotalFrames(): Check how many frames are in the movie.
    • Rewind(): Go to frame 1 and stop.
    • SetZoomRect (x1,y1,x2,y2): Zoom on rectangle with the coordinates (top left: x1,y1) (bottom right: x2,y2). Units are TWIPS. There are 1440 TWIPS in an inch, and 20 TWIPS in a single point.
    • Zoom(percent):Zoom in. Opposite of what you'd expect:
      Zoom(50) = 2 times movie size
      Zoom(200) = 1/2 movie size
      Zoom(0) = back to original size
    • Pan (x,y,mode): Move around a zoomed in movie. "mode" should be set to "0" to move in pixels, and "1" to move in percentage.
    • PercentLoaded(): Check how much of the movie has downloaded to the browser. Returns a value between 0 and 100.


    Flash 3.0+ Methods
    In Flash 3, Movie Clips can be controlled by the "Tell Target" action. The methods added in Flash 3.0 are mostly controls for Movie Clips, and work the same way as internal "Tell Target" actions. The exception is "LoadMovie" which behaves as an internal LoadMovie action does. Notes: 1) the syntax you'll need to use for the Tell Target methods is given as an example of TGotoFrame and TGotoLabel, 2) in all Tell Target methods, the value of "target" must be a string enclosed in quotation marks. The value of "framenumber" must be an integer.

    • TGotoFrame(target, framenumber)
      In the "target" movie clip, goto frame "framenumber". Note that "framenumber" starts at 0 in JavaScript, but at 1 in Flash, so TGotoFrame("level0/",5) will actually go to frame 6.
      eg1: TGotoFrame("_level0/",5)
         On the main movie timeline, go to frame 6.
      eg2: TGotoFrame("_level0/colours",5)
         In the Movie Clip named "colours", go to frame 6.
    • TGotoLabel(target, frame label)
      On the main movie timeline, go to the specified frame label.
      eg1: TGotoLabel("_level0/","redframe")
         On the main movie, go to the frame labeled "redframe".
      eg2: TGotoLabel("_level0/colours","greenframe")
         In the Movie Clip named "colours", go to the frame labeled "greenframe".
    • TCurrentFrame(target): Returns the number of the frame on which the playback head rests when the method is called. Use "_level0/" as the target for the main timeline.
    • String TCurrentLabel(target): Returns the label of the frame on which the playback head rests when the method is called. Returns null if no the frame is not labeled. Use "_level0/" as the target for the main timeline.
    • TPlay(target): Play the specified Movie Clip.
    • TStopPlay(target): Stop the specified Movie Clip.
    • LoadMovie(layer,url): Load a movie onto "layer" from "url". Note that the value of layer must be an integer, while url must be a string enclosed in quotation marks.


    Flash 4.0+ Methods
    see http://www.macromedia.com/support/flash/publishexport/scriptingwithflash/scriptingwithflash_03.html

References
Macromedia's Technote 04160 (Scripting with Flash)
The first developer article on scripting with Flash. Most of the technical information about FS Command is there, but the content is aimed at experienced developers.

Macromedia's Scripting with Flash Tutorial
A well written article covering both JavaScript Flash method usage and fscommand().

Macromedia's Creating a smarter Site Navigation Bar with Flash and JavaScript
A short discussion on how to use JavaScript to maintain the state of a Flash navigation bar across frames. Thin from a documentation standpoint, but useful for its sample code. [NOTE: THE ABOVE ARTICLE IS NO LONGER AVAILABLE AT MACROMEDIA'S SITE, BUT CAN BE READ AT THE WAYBACK MACHINE'S WEB ARCHIVE.]

Macromedia's Hawaii Map Demo
Originally a sample site by Jon Gay, (the inventor of Flash), which demonstrates some of the things you can do with FS Command. This demo is now up at Flash Central. Again, good for the samples, but light on documentation. You'll have to root around with View Source...

Macromedia's Scripting with Flash and ActiveX
A list of the ActiveX-only (ie. *not* Netscape) methods available with Flash.

John Croteau's JavaScript/Flash Clock Tutorial
A well written, in depth tutorial on making a clock in Flash movies that's run by JavaScript. A good application of FS Command that's worth checking out once you're familiar with FS Command basics.

John Croteau's FS Command Methods Table
A complete spread-sheet style table listing the FS Command methods for JavaScript, the stand-alone player, and ActiveX.

Revision History
  1. January 10, 1999: Posted.
  2. January 25, 1999: Reworded "Support for FS Command" section to make list of supported browsers clearer.
  3. February 17, 1999: Added VBSCRIPT comment ("//-->"). Fixed reversed JavaScript comment (cut'n'paste code only).
  4. February 22, 1999: Fixed typo in cut'n'paste code (line was: var movie_ready == "false";).
  5. April 22, 1999: Fixed a couple of typos in the article copy.
  6. May 5, 1999: Fixed link to Jon Gay's Hawaii Map demo. Jon's site at Macromedia was taken down...
  7. Sept 14, 1999: Added link to Macromedia's Flash 4 FS Command article that covers ActionScript methods.
  8. Sept 14, 1999: Added some missing </SCRIPT> tags in the cut'n'paste code for step 2 of javascript->flash communication. thanks to dave hollinden for noticing that.
  9. july 04, 2000: added a link to macromedia's flash 4 methods table, and did some general cleanup.
  10. november 14, 2000: added note about netscape 6's lack of support for liveconnect.
  11. july 03, 2001: fixed minor error in TGotoFrame method description. thanks to rod savoie for pointing it out.
  12. july 24, 2001: removed some dead reference links, updated the javascript samples, and revised the article to use flash 5 concepts and syntax.
  13. august 02, 2001: added an object-check to the isMovieLoaded() function in the javascript-to-flash.html sample. also added note about using getURL() to talk to javascript instead of fscommand().
  14. february 16, 2003: updated list of supported browsers to discuss Netscape 6.2
  15. july 4, 2005: added a link to the Flash/JavaScript Integration Kit