PASSING VARIABLES FROM HTML TO FLASH VIA FLASH VARS
(USING AS3)
 

 

OVERVIEW

 
    
This tutorial is for ActionScript3.  For ActionScript 1 and 2 go here.  If you're not familiar with FlashVars, I recommend reading  the overview there first, then returning to this page for the AS3 examples.

The main difference between AS2 and AS3 is how to retrieve the FlashVars. The FlashVars are no longer available in the _root level of the movie. Instead, you must use the new LoaderInfo class object to access the FlashVars.  The FlashVars is available in the parameters member of the LoaderInfo.  An example below show how to load a FlashVars named"userName" onto a text field named userNameTextField.

In case you're wondering where the loaderInfo comes from, it comes from MovieClip's ancestors. The stage MovieClip is derived from InteractiveObject, which derives from DisplayObject. If you examnle the DisplayObject class, you will see one of the member variables is the LoaderInfo.

MovieClip -> InteractiveObject->DisplayObject


ValueClick Media Online Advertising Network
 
function loaderComplete(myEvent:Event)
{
  var flashVars=this.loaderInfo.parameters;
  userNameTextField.text=flashVars.userName;
}

this.loaderInfo.addEventListener(Event.COMPLETE, loaderComplete);

Note that we trap the Event.COMPLETE message to make sure that the swf has finished loading before we start using the FlashVars.

You might be wondering what to do if you want to access the FlashVars outside of the loaderComplete() function above.  An obvious way is to use this.loaderInfo.parameters, but that is cumbersome.  Instead, you can set the FlashVars as a member of your own object. 

Here's an example where I assigned the FlashVars to be member of myFlashVars.  This is for illustration purpose.  It is,of course, better to create a class to handle this repetitive task rather than putting this on the main timeline. 

//////////////////////////////////////////////
function loaderComplete(myEvent:Event)
{
   this.flashVars=this.loaderInfo.parameters;
   this.flashVarsLoaded=true;  // set a flag to indicate that the FlashVars is loaded
   this.useFlashVars();
}


//////////////////////////////////////////////
function useFlashVars()
{
  // dome something with the flash vars
}

// This object will hold my FlashVars, eq: myFlashVars.flashVars.userName;
var myFlashVars=new Object();      
// Set a flag indicating that the FlashVars is not loaded yet.
// Anytime you want to use the FlashVars,
// make sure this flag has been set to true.
myFlashVars.flashVarsLoaded=false;


// Use this as callback for Event.COMPLETE
myFlashVars.loaderComplete=loaderComplete;



myFlashVars.useFlashVars=useFlashVars;


// Tells the LoaderInfo to call myFlashVars.loaderComplete when the movie is loaded.
// The FlashVars will be saved as member of "myFlashVars"
// For instance, if I have a FlashVar named "userName," it will be accessible as
// myFlashVars.flashVars.userName
this.loaderInfo.addEventListener(Event.COMPLETE, myFlashVars.loaderComplete);

See this example
Download FLA
 

 

EXAMPLE 1
Maximizing Code Reuse

 
    
In this contrived example, suppose that you have a Flash movie that loads an image file and display the image. 

You want to be able to use the same swf file on many pages to show different images.  Obviously, you need to pass the image filename to Flash.  What can you do?  Since a filename is such a simple text, you can use FlashVars to pass it.  

Assuming that the image filename is image1.jpg, and that it is located at a folder named images.  And assuming that the Flash movie will use a variable named imageFilename to refer to the file, then we can do this:

<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
 codebase=""http://macromedia.com/cabs/swflash.cab#version=9,0,0,0""
 WIDTH="250" HEIGHT="250" id="flaMovie1as3" ALIGN="CENTER">
 <PARAM NAME=movie VALUE="flaMovie1as3.swf">
 <PARAM NAME=FlashVars VALUE="imageFilename=images%2Fimage1%2Ejpg">
 <PARAM NAME=quality VALUE=high>
 <PARAM NAME=bgcolor VALUE=#FFFFFF>
 <embed src="flaMovie1as3.swf" FlashVars="imageFilename=images%2Fimage1%2Ejpg"
  quality="high" bgcolor="#FFFFFF" WIDTH="250" HEIGHT="250"
  NAME="flaMovie1as3" ALIGN TYPE="application/x-shockwave-flash"
  PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer">
</OBJECT>

You can see that the FlashVars contains one variable: imageFilename, with the value of "images/image1.jpg".  

Note: The %2F is the URL encoding for the "/" sign, and %2E is the URL encoding for the "." sign.  Since these symbols are unsafe or reserved, we should URL encode them, although at the present Flash does not seem to care.  So saying: imageFilename=images%2Fimage1%2Ejpg is essentially the same as saying imageFilename=images/image1.jpg (See: Introduction to URL Encoding)

In AS3, the FlashVars are no longer accessible in _root.  Instead, you need to use LoaderInfo to access them.  An example is below:

// This function will be called when the swf finished loading.
// Suppose I have a movie clip names "mc" on the stage, this rootComplete() function will load the
// imageFilename specified in the FlashVars.
function loaderComplete(myEvent:Event)
{
  var flashVars=this.root.loaderInfo.parameters;
  imageFilenameTextField.text=flashVars.imageFilename;
  var loader = new Loader();
  mc.addChild(loader);
  loader.load(new URLRequest(flashVars.imageFilename));
}

// This assigns the callback to be called when the movie has finished loading.
this.loaderInfo.addEventListener(Event.COMPLETE, loaderComplete);

Download FLA (Use the object tag above to see it working, make sure you have an image subfolder on the folder where the swf file is located.  The subfolder should contain the image specified in imageFIlename).

Here are example of the swf file with different FlashVars:
"imageFilename=images/image1.jpg"

"imageFilename=images/image2.jpg"

 
 
 

EXAMPLE 2
Passing Cookie Data

 
 

 
Suppose that you have a Flash movie that displays the current user name.  The Flash movie needs to retrieve the user name from a cookie. 

You can pass the cookie value into Flash via loadVariables (with CGI); or even using JavaScript and FSCommand (see here).  But, since a user name is a fairly simple data, let's see how it can be done with FlashVars.  Note: FlashVars is not safe, user can see it.  Anything confidential like a password should NEVER be passed via FlashVars.

Because you don't even know who the user will be, you cannot hard code it in the html page.   That is, you cannot put: "userName=jim2000" in the html code since userName might be jane2.   So, in this case, we must use another way to write the proper FlashVars.  This requires being able to write the FlashVars on the fly, as will be explored later.   Let's first create a cookie.  Enter a user name below then click the button.   When the button is clicked, a cookie named "userName" will be created for you (JavaScript must be enabled for this example to work properly): 

 
 

  

Please enter userName  

In the flash file, the variable userName can be accessed such as this:

// This function will be called when the swf finished loading.
// Suppose I have a text field named "userNameTextField" on the stage,
// this loaderComplete() function will assign the text of the textfield to the userName
// specified in the FlashVars.
function loaderComplete(myEvent:Event)
{
  var flashVars=this.loaderInfo.parameters;
  userNameTextField.text=flashVars.userName;
}

this.loaderInfo.addEventListener(Event.COMPLETE, loaderComplete);

Download FLA (Note, use the object tag below to see it working).

Because Flash does not support cookie reading directly, we need to use a scripting language to read the cookie first, and then pass the data as FlashVars.   I will show 3 examples.  The first one uses ASP, and the second one uses JavaScript, and the last one uses PHP.  

USING ASP

Below is an example of using ASP to get the cookie value and pass the value to the FlashVars.  

<%
  swfTag = _
    "<OBJECT classid=""clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"""& vbCrLf & _
    "  codebase=""http://macromedia.com/cabs/swflash.cab#version=9,0,0,0"""& vbCrLf & _
    "  ID=flaMovie2as3 WIDTH=250 HEIGHT=75>"& vbCrLf & _
    "  <PARAM NAME=FlashVars VALUE=""userName=" & _
        Server.URLEncode(Request.Cookies("userName")) & """>" & vbCrLf & _
    "  <PARAM NAME=movie VALUE=""flaMovie2as3.swf"">"& vbCrLf & _
    "  <PARAM NAME=quality VALUE=medium>"& vbCrLf & _
    "  <PARAM NAME=bgcolor VALUE=#99CC33>"& vbCrLf & _
    "  <EMBED src=""flaMovie2as3.swf"" " &_
    "    FlashVars=""userName=" & Server.URLEncode(Request.Cookies("userName")) &""""& vbCrLf & _
    "    bgcolor=#99CC33 WIDTH=250 HEIGHT=75 "& vbCrLf & _
    "    TYPE=""application/x-shockwave-flash"">"& vbCrLf & _
    "  </EMBED>"& vbCrLf & _
    "</OBJECT>"

 'writes out the OBJECT string
 Response.Write swfTag
%>

Notice that I added lots of carriage returns (vbCrLf) so that the resulting code will be easier to debug.  (Ie: when you open the page and view the page source, this prevents having everything written on a single line.)

When that code is run, the line Request.Cookies("userName") will be replaced with the userName stored in the cookieThe Server.URLEncode() call encodes a string to make sure that special characters in the string are URL encoded.  Without this, if the userName contains special characters, such as the "&" character in: John & Associates, then the result will become unpredictable.

Click here to see the page generated by the script above.  (Remember to set the cookie first using the form above, or the result will be undefined)

You can do it more cleanly and efficiently with a code like below (even better, you should consider writing a function if you use the code often):

<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
  codebase="http://macromedia.com/cabs/swflash.cab#version=9,0,0,0"
  ID=flaMovieas3 WIDTH=250 HEIGHT=75>
  <PARAM NAME=movie VALUE="flaMovie2as3.swf">
  <PARAM NAME=FlashVars VALUE="userName=<%=Server.URLEncode(Request.Cookies("userName"))%>">
  <PARAM NAME=quality VALUE=medium>
  <PARAM NAME=bgcolor VALUE=#99CC33>
  <EMBED src="flaMovie2as3.swf" 
    FlashVars="userName=<%=Server.URLEncode(Request.Cookies("userName"))%>"
    bgcolor=#99CC33 WIDTH=250 HEIGHT=75
    TYPE="application/x-shockwave-flash">
  </EMBED>
</OBJECT>

 
Click here to see the page generated by the script above.  (Remember to set the cookie first using the form above, or the result will be undefined)

USING JAVASCRIPT

With JavaScript, the process is similar.  You can use document.write to pass the cookie values.  You will need to write the entire <object> tag, since JavaScript is a client side scripting language, and you can't run a JavaScript code nested within an <object> tag.  An example is shown below.  

<HTML>
<HEAD><TITLE>Example</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!--
// a simple function that returns the value of a cookie
function getCookie(name)
{
  if (document.cookie)
  {
    var cookies=document.cookie.split(";");
    for (var i=0; i<cookies.length; i++)
    {
      var varName=(cookies[i].split("=")[0]);
      var varValue=(cookies[i].split("=")[1]);

      // the next 2 lines trim whitespaces (Netscape 7 problem)
      while (varName.charAt(0)==" ")
        varName=varName.substr(1,varName.length);
      if (varName==name)
	return escape(varValue);
    }
  }
}
//-->
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
<!--
// The code below writes out the OBJECT tag.
// You might want to create a function that
//  takes some parameters (swf name, width, height, etc)
//  instead of hard coding eveyrthing like this
document.write(
  '<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"\n'+
  '  codebase="http://macromedia.com/cabs/swflash.cab#version=9,0,0,0"\n'+
  '  ID=flaMovie WIDTH=250 HEIGHT=75>\n'+
  '  <PARAM NAME=movie VALUE="flaMovie2as3.swf">\n'+
  '  <PARAM NAME=FlashVars VALUE="userName=' + getCookie('userName')+'">\n'+
  '  <PARAM NAME=quality VALUE=medium>\n'+
  '  <PARAM NAME=bgcolor VALUE=#99CC33>\n'+
  '  <EMBED src="flaMovie2as3.swf" FlashVars="userName=' + getCookie('userName')+'"\n'+
  '    bgcolor=#99CC33 WIDTH=250 HEIGHT=250 \n'+
  '    TYPE="application/x-shockwave-flash">\n'+
  '  </EMBED>\n'+
  '</OBJECT>\n');
//-->
</SCRIPT>
</BODY>
</HTML>

Note: Coding document.writes like above is very error prone and hard to debug because when you do View Source after opening the document, you don't see what the being written by the document.writes.  Sometimes you forget to put a closing tag or a closing ">" and don't know why the page won't load.  The easiest way for me to debug this kind of code is to use an older Netscape 4.8 browser.  That older browser (at least the PC version) shows the result of document.writes when you do View Source.  This is also why I appended the \n (start anew new line) often: to make it easier to see the result.

The escape() function in getCookie() encodes the cookie value to make sure that if there're special characters in the string, that they will be URL encoded.  Without this, if the userName contains special characters, such as the "&" character in: John & Associates, then the result will become unpredictable.  Note however, that the escape() function does not encode '+' and '/' characters.  For a workaround, see here.

Click here to see the page generated by the script above.  (Remember to set the cookie first using the form above, or the result will be undefined)
  

USING PHP
  
This example is for PHP 4 or above.

<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
  codebase="http://macromedia.com/cabs/swflash.cab#version=6,0,0,0"
  ID=flaMovie WIDTH=250 HEIGHT=250>
  <PARAM NAME=movie VALUE="flaMovie2as3.swf">
  <PARAM NAME=FlashVars VALUE="userName=<?php echo(urlencode($userName));?>">
  <PARAM NAME=quality VALUE=medium>
  <PARAM NAME=bgcolor VALUE=#99CC33>
  <EMBED src="flaMovie2as3.swf" FlashVars="userName=<?php echo(urlencode($userName));?>"
    bgcolor=#99CC33 WIDTH=250 HEIGHT=250
    TYPE="application/x-shockwave-flash">
  </EMBED>
</OBJECT>

Or, using $HTTP_COOKIE_VARS[]:

<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
  codebase="http://macromedia.com/cabs/swflash.cab#version=6,0,0,0"
  ID=flaMovie WIDTH=250 HEIGHT=250>
  <PARAM NAME=movie VALUE="flaMovie2as3.swf">
  <PARAM NAME=FlashVars VALUE="userName=<?php echo(urlencode($HTTP_COOKIE_VARS["userName"]));?>">
  <PARAM NAME=quality VALUE=medium>
  <PARAM NAME=bgcolor VALUE=#99CC33>
  <EMBED src="flaMovie2as3.swf" 
    FlashVars="userName=<?php echo(urlencode($HTTP_COOKIE_VARS["userName"]));?>"
    bgcolor=#99CC33 WIDTH=250 HEIGHT=250
    TYPE="application/x-shockwave-flash">
  </EMBED>
</OBJECT>

When that code is run, the line $userName (which is the same as $HTTP_COOKIE_VARS["userName"]) will be replaced with the userName stored in the cookieThe urlencode() function encodes the string to make sure that special characters in the string are URL encoded.  Without this, if the userName contains special characters, such as the "&" character in: John & Associates, then the result will become unpredictable.

Click here to see the page generated by the script above.  (Remember to set the cookie first using the form above, or the result will be undefined)
  

 
 

EXAMPLE 3
Passing HTTP Query String to Flash

 
 


Suppose I have a form page that opens another html page like below.  

Please enter your user name   (<input type="text" name="UserName")
Please enter your company name (<input type="text" name="CompanyName")
    

The form action is set as follows:  <form method="GET" action="form.html">.  This will cause the UserName and CompanyName variables to be sent to the query string when you click the Submit button.

// This function will be called when the swf finished loading.
// Suppose I have a text field named "userNameTextField" on the stage,
// this loaderComplete() function will assign the text of the textfield to the userName
// specified in the FlashVars.
function loaderComplete(myEvent:Event)
{
  var flashVars=this.loaderInfo.parameters;
  CompanyNameTextField.text=flashVars.CompanyName;
  UserNameTextField.text=flashVars.UserName;
}

this.loaderInfo.addEventListener(Event.COMPLETE, loaderComplete);

Download FLA (Note, use the object tag below to see it working).

After you click the Submit button above, then form.html will be opened.  The Address/URL bar will look like below:


This Flash movie contains two textboxes.  The top one will print the value of _root.UserName, the bottom one will print the value of _root.CompanyName.  These variables are retrieved from the query string.  You can see how the query string is passed later in this tutorial.

You should see something like above (assuming you have JavaScript enabled).   I entered jim as UserName and The Company as CompanyName.  As you can see in the Address bar above, the form data is appended as a query string.  This is done automatically by the GET method of the <form> tag.  I marked the query string portion in red:

http://www.permadi.com/tutorial/flashVars/form.html?UserName=jim&CompanyName=The+Company

So far so good, now we need to pass this query string to Flash.

USING JAVASCRIPT

Using JavaScript, you can get the address of the current page by using location property of the document object.   So, in the above example, the document.location will contain the value of http://www.permadi.com/tutorial/flashVars/form.html?UserName=jim&CompanyName=The+Company

Just for fun, click here to see what the value of document.location of this page.  You can also just get the query string portion by using document.location.search (the name "search" probably comes from early days of the internet where query string is mostly used by search engines?).  In the above example, document.location.search will contain the value of 
?UserName=jim&CompanyName=The+Company

If you're curious, resubmit the form above and see what the value of document.location.search of that page is.  Click the Submit and Use JavaScript button; a new page with a Flash movie will open; then use the button below the Flash movie).  If you leave the default values, it should say: 

Note that the "?" sign is included, which is weird because it isn't really part of the query string.   To form the proper FlashVars we need to remove that sign.  This is done in the blue section below by checking if the first character is a "?" character, and removing it if it is.

<HTML><HEAD><TITLE>Example</TITLE></HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
<!--
 var myQueryString=document.location.search;

 // remove the '?' sign if exists
 if (myQueryString[0]='?')
 {
    myQueryString=myQueryString.substr(1, myQueryString.length-1);
 }

 document.write(
   '<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"\n'+
   ' codebase="http://macromedia.com/cabs/swflash.cab#version=6,0,0,0"\n'+
   ' WIDTH="250" HEIGHT="250" id="flaMovie1">\n'+
   ' <PARAM NAME=movie VALUE="flaMovie3as3.swf">\n'+
   ' <PARAM NAME=FlashVars VALUE="'+myQueryString+'">\n'+
   ' <PARAM NAME=quality VALUE=high>\n'+
   ' <PARAM NAME=bgcolor VALUE=#FFFFFF>\n'+
   ' <EMBED src="flaMovie3as3.swf"\n'+
   '  FlashVars="'+myQueryString+'"\n'+
   '  quality=high bgcolor=#FFFFFF  WIDTH="250" HEIGHT="250" NAME="flaMovie1"\n'+
   '  TYPE="application/x-shockwave-flash"\n'+
   '  PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer"></EMBED>\n'+
   '</OBJECT>');

 //-->
 </SCRIPT>
</BODY>
</HTML>

Try it below:

Please enter your user name   (<input type="text" name="UserName")
Please enter your company name (<input type="text" name="CompanyName")
    

Note:

  • On JavaScript 1.2, the location property of the document  is depreciated (but still available) and is being replaced by URL (all capitals).  You can replace document.location with window.location.  Also, document.location.search is the same as window.location.search and location.search (assuming you don't have local variables with that same name)

USING ASP

With ASP, you can do something similar using the Request.QueryString object.  Here's an example of it.

<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
  codebase="http://macromedia.com/cabs/swflash.cab#version=6,0,0,0"
  ID=flaMovie WIDTH=250 HEIGHT=250>
  <PARAM NAME=movie VALUE="flaMovie3as3.swf">
  <PARAM NAME=quality VALUE=medium>
  <PARAM NAME=bgcolor VALUE=#99CC33>
  <PARAM NAME=FlashVars VALUE="<%=Request.QueryString%>">
  <EMBED src="flaMovie3as3.swf" FlashVars="<%=Request.QueryString%>"
    bgcolor=#99CC33 WIDTH=250 HEIGHT=250
    TYPE="application/x-shockwave-flash">
  </EMBED>
</OBJECT>

You can try that ASP code using the form below.  The form uses <form method="GET" action="formasp.asp">.   When you click the Submit and Use ASP button, the UserName and CompanyName will be passed as a query string to the formasp.asp, which executes the code above.

Please enter your user name   (<input type="text" name="UserName")
Please enter your company name   (<input type="text" name="CompanyName")
    

  
USING PHP

With PHP, you can do something similar using the $QUERY_STRING or $HTTP_GET_VARS variable.   Here's an example of it.

<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
  codebase="http://macromedia.com/cabs/swflash.cab#version=6,0,0,0"
  ID=flaMovie WIDTH=250 HEIGHT=250>
  <PARAM NAME=movie VALUE="flaMovie3as3.swf">
  <PARAM NAME=FlashVars VALUE="<?php echo($QUERY_STRING);?>">
  <PARAM NAME=quality VALUE=medium>
  <PARAM NAME=bgcolor VALUE=#99CC33>
  <EMBED src="flaMovie3as3.swf" FlashVars="<?php echo($QUERY_STRING);?>"
    bgcolor=#99CC33 WIDTH=250 HEIGHT=250
    TYPE="application/x-shockwave-flash">
  </EMBED>
</OBJECT>

The form uses <form method="GET" action="formphp.php">.   When you click the Submit and Use PHP button, the UserName and CompanyName will be passed as a query string to the formphp.php, which executes the code above.

Please enter your user name   (<input type="text" name="UserName")
Please enter your company name   (<input type="text" name="CompanyName")
    

You can do the same thing using other scripting languages. 

Here's another LoaderInfor example to load query strings.

 
 

Terms of Use

permadi@permadi.com

 
(C) F. Permadi

<<INDEX>>