PASSING
VARIABLES FROM HTML TO FLASH VIA FLASH VARS
OVERVIEW
Note: This tutorial is for ActionScript 1 and 2.
For ActionScript3 user, I recommend reading this OVERVIEW
and then go
here for
ActionScript3 examples.
This tutorial is very similar to another tutorial elsewhere
on this site about Passing
Variables From HTML to Flash via Query String. The
main difference is in the syntax; and the difference is fairly
minor. Also, FlashVars only works with Flash Player 6
(that is Flash MX) or newer.
What is FlashVars?
FlashVars is Flash answer to Query String. It's a
way to pass data or variables from html to a Flash movie. The
general idea of FlashVars is very similar to a
Query String. Variables passed via FlashVars will go
into the _root level of the Flash movie.
Why and When to use Flash Vars Using FlashVars is very easy and it is a good
alternative to using Query String. It is suitable for situations such as
these:
The data to be passed is fairly simple. By simple,
I mean simple text (such as user name, filename, id, or cookie
info).
You don't care about the security of the data.
Any user can
easily see the content of the FlashVars by viewing the page source.
Something like a password should NEVER
be passed via FlashVars.
Some other characteristics of FlashVars:
The size limit of a FlashVars file is 64K (more than 65,000
bytes or between 32,500 to 65,000 characters,
depending on the encoding).
FlashVars is supported by Flash
Player 6 and newer. It is not supported in Flash 5. If you need to support Flash Player
5, you can read more about using Query
String.
FlashVars Syntax
When you put a Flash movie on a html
page, you will have an OBJECT and EMBED tag code that is similar
to this:
Both tags serve the same purpose, to specify a Flash
movie. However, most Netscape browsers only understand EMBED
tags, while Internet Explorer only understand OBJECT
tags. Whenever you specify a Flash movie, you should use
both. So, when using FlashVars, there are also two
slightly different syntax, one for the OBJECT tag, and
the other one for EMBED tag.
For the OBJECT tag, the syntax is as follows:
<PARAM NAME FlashVars VALUE=[variable1=value1&variable2=value2&variable3=value3...]>
The param tag must be nested within the OBJECT
tag.
Each
variable variable and value pair is separated by a '='
sign. A '&'sign separates the each pair.
So for example, if I have two variables, userName and score,
the tags would look like this:
Several things that should be noted about variable names:
Use only letters, underline, and numbers. There
should be no reason why symbols such as '$' or '#' must be
used as variable names.
Do not start a name with a number (for example: 1message
is an invalid variable name because it starts with a
number; whereas message1 is a
valid variable name).
Flash will certainly reject
or get confused if you use a
variable name that starts with a number or other special
characters - except underlines (ie: _message, and _1message
are valid names).
A variable name should not contain any <space>
character (ie: my message is an invalid name,
my_message is a valid name).
And for variable values, there are also rules:
Characters needs to be URL encoded (see:
Introduction to
URL Encoding). This means
that special characters, such as =, &, <SPACE>,
+ need to be substituted with their URL encoded
form. For example: name=John Doe. Here, the <space>
between John and Doe needs
to be encoded with + sign, so you need to pass it
as name=John+Doe or name=John%20Doe. (Flash doesn't seem to
enforce this, but you should follow the proper way.)
Search for URL encoding on the net for more details on
this subject.
If you need to include an & as part
of a value, such as in ingredients=Beef&Pork, then you need to encode the & like
this: ingredients=Beef%26Pork. The %26
is an encoded form of the & sign. The number
26 is the hexadecimal code of the character &.
If you
need to know the encoding value of a particular character, consult
an ASCII table.
There are other characters that need to be
encoded, such as <, >, /, ?.
Note: The remaining of this tutorial is for ActionScript 1 and 2. For
ActionScript3 go
here.
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:
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 this way, when the Flash movie starts, that movie will have a
variable named imageFilename within its _root. Then, I can say:
loadMovie(_root.imageFilename); and to load the
specified image file.
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):
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.
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
cookie. The 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.
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=6,0,0,0"\n'+
' ID=flaMovie WIDTH=250 HEIGHT=75>\n'+
' <PARAM NAME=movie VALUE="flaMovie2.swf">\n'+
' <PARAM NAME=FlashVars VALUE="userName=' + getCookie('userName')+'">\n'+
' <PARAM NAME=quality VALUE=medium>\n'+
' <PARAM NAME=bgcolor VALUE=#99CC33>\n'+
' <EMBED src="flaMovie2.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.
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
cookie. The 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.
Suppose I have a form page that opens another html page
like below.
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.
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, thebottom
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:
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.
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.
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.
USING PHP
With PHP, you can do something similar using the $QUERY_STRING
or $HTTP_GET_VARS variable. Here's an example of it.
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.
You can do the same thing using other scripting languages.