Using FlashVars with ActionScript 3.0
I was building a small app in Flash/ActionScript 3.0 over the weekend and needed to find out how to use FlashVars (Using FlashVars to pass variables to a SWF) to pass variables to my SWF file.
Previously, in ActionScript 2.0, you could pass variables along the query string or using FlashVars and the variables would be available in _level0, in ActionScript 3.0, it is a bit tricker:
<!-- using query string -->
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0"
width="550"
height="400"
align="middle"
id="main">
<param name="allowScriptAccess" value="sameDomain" />
<param name="movie" value="main.swf?one=1&two=2" />
<param name="quality" value="high" />
<param name="bgcolor" value="#ffffff" />
<embed src="main.swf?one=1&two=2"
width="550"
height="400"
autostart="false"
quality="high"
bgcolor="#ffffff"
name="main"
align="middle"
allowScriptAccess="sameDomain"
type="application/x-shockwave-flash"
pluginspage="http://www.macromedia.com/go/getflashplayer" />
</object>
The previous code passes two variables (one and two) along the querystring (main.swf?one=1&two=2) and makes those variables available in your SWF file in the root's loaderInfo object (or more accurately, within the loaderInfo's parameters property).
Also, the same technique works if you pass the variables within a FlashVars parameter, as seen below:
<!-- using FlashVars -->
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0"
width="550"
height="400"
align="middle"
id="main">
<param name="allowScriptAccess" value="sameDomain" />
<param name="movie" value="main.swf" />
<param name="quality" value="high" />
<param name="bgcolor" value="#ffffff" />
<param name="FlashVars" value="one=1&two=2" />
<embed src="main.swf"
width="550"
height="400"
autostart="false"
quality="high"
bgcolor="#ffffff"
FlashVars="one=1&two=2"
name="main"
align="middle"
allowScriptAccess="sameDomain"
type="application/x-shockwave-flash"
pluginspage="http://www.macromedia.com/go/getflashplayer" />
</object>
But enough of my rambling, how do you access these from within your FLA document? Read on!
// AS3
var tf:TextField = new TextField();
tf.autoSize = TextFieldAutoSize.LEFT;
tf.border = true;
addChild(tf);
tf.appendText("params:" + "\n");
try {
var keyStr:String;
var valueStr:String;
var paramObj:Object = LoaderInfo(this.root.loaderInfo).parameters;
for (keyStr in paramObj) {
valueStr = String(paramObj[keyStr]);
tf.appendText("\t" + keyStr + ":\t" + valueStr + "\n");
}
} catch (error:Error) {
tf.appendText(error.toString());
}
The previous code creates a new TextField instance on the Stage (named tf), uses a for..in loop to iterate over each of the passed parameters and displays the parameter's names and values in the text field.
Nothing ground breaking or overly fascinating, but hopefully this helps somebody out there or saves them about 3 minutes of searching.
Comments
Hello,
In actionscript 2.0 can I use a for..in loop with loaderInfo parameters to look at the flashVars paramenters? I tried to look up LoaderInfo but found nothing except actionscript 3.0 refrences.
Posted by: JOsH | September 5, 2006 01:06 PM
Hello,
In actionscript 2.0 can I use a for..in loop with loaderInfo parameters to look at the flashVars paramenters? I tried to look up LoaderInfo but found nothing except actionscript 3.0 refrences.
Posted by: JOsH | September 5, 2006 01:34 PM
Thanks so much... How about an example for Flex 2.0 ?
Also, love to see a quick way of passing values to Javascript function that then passes it to a flex 2.0 swf a page.
The Flex / Ajax bridge seems a bit over kill (setup etc) if all I want to do is pass a couple of params to my flex ap.
Any thoughts?
Posted by: Dan Zeitman | October 10, 2006 06:40 AM
Hi there
Useful post, but how does one access the root variable in an Flex Actionscript application - i.e. not via the timeline.
In this case the value of root is null because it hasn't been initialized yet, and the code below throws an error:
LoaderInfo(this.root.loaderInfo).parameters;
Posted by: Tracy | November 6, 2006 12:20 AM
So, the try-catch will continue to work with errors even if it stops - as in local tests.
I'm learning that there's usually both a flex and flash way at solutions in AS 3.0.
Patrick
Posted by: Patrick | February 20, 2007 06:09 PM
OK, to recap, i tried this approach with the flex sdk and it does not work. There seems to be no information on this elsewhere.
Thanks,
Patrick
Posted by: Patrick Lemiuex | February 21, 2007 05:01 PM
How do you do this with the SDK, without timeline access, the above does not work.
Thanks,
Patrick
Posted by: Patrick Lemiuex | February 21, 2007 05:14 PM
How to get flash var values with FLEX and AS3:
http://www.abdulqabiz.com/blog/archives/macromedia_flex/how_to_get_url.php
Basically,
mx.core.Application.application.parameters.name
Where "name" is the name of the flashvar. So for the example of this page:
mx.core.Application.application.parameters.one
mx.core.Application.application.parameters.two
Posted by: Gabriel | March 2, 2007 01:40 PM
Is there a way to do this process without connecting to the Web? I'm trying to develop a survey that will give users feedback at the end based on how the questions are answered. There will be no Internet connection.
Posted by: Deborah Thomas | April 16, 2007 12:29 PM
Thanks. Always nice to google and get a working recipe as the first link.
Posted by: Sam | June 22, 2007 05:41 PM
Perfect this was exactly what I was searching for. Except in the final line the word error should be in quotes....
tf.appendText("error");
Otherwise, you'll get this message... 1067: Implicit coercion of a value of type Error to an unrelated type String.
Posted by: Justin | June 22, 2007 11:58 PM
Thanks, this helped a lot!
Posted by: Andrew Paul Simmons | June 28, 2007 05:02 PM
can you help me figuring this problem? i am trying to create a flash menu from this site, i want a single flash file to be used. i am figuring out how to make the menu be the default (different effect form the others) per page, using a single flash file. i am new to flashVars(to be honest no knowledge at all -for now)... i am desperate to seek some help... please help me... thanks
Posted by: michael | June 28, 2007 11:00 PM
I have tried both methods described to pass variables from HTML page to Flash. Works fine unless I access the page remotely. What's catch? Security restrictions?
Posted by: Marc | July 25, 2007 03:23 AM
Marc,
Can you clarify what you mean by "unless I access the page remotely"?
Peter
Posted by: Peter | July 25, 2007 09:34 AM
Self-made recovery: flash content should be fully loaded before attempting to access variables. Preloading solves the problem.
Posted by: Marek | July 26, 2007 06:19 AM
Thanks, Peter! Saved me valuable time, and worked like a charm. :)
Posted by: lisamarienyc | July 27, 2007 03:59 PM
That is exactly what I was looking for. Thanks!
Posted by: somethingkindawierd | August 8, 2007 01:00 PM
In Flex 2.0 it is slightly different:
package {
//dependencies
import flash.display.Sprite;
flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.display.LoaderInfo;
//Set swf properties
[SWF(width="640", height="480", backgroundColor="#FFFFFF", frameRate="30", scale="showall")]
public class FlashvarsInFlex2Test extends Sprite
{
public function FlashvarsInFlex2Test()
{
var tf:TextField = new TextField();
tf.autoSize = TextFieldAutoSize.LEFT;
tf.border = true;
addChild(tf);
tf.appendText("flashvars:" + "\n");
try {
var keyStr:String;
var valueStr:String;
var paramObj:Object = root.loaderInfo.parameters;
for (keyStr in paramObj) {
valueStr = String(paramObj[keyStr]);
tf.appendText("\t" + keyStr + ":\t" + valueStr + "\n");
}
} catch (error:Error) {
tf.appendText(""+error);
}
}
}
}
Posted by: James Tindall | August 23, 2007 03:47 AM
Thank you so much for this tutorial. I spent about 4 hours yesterday, trying to pass a simple variable from the container HTML with no success (using AS3). If Adobe can update the FlashVars section of the documentation, it would be a great help.
Posted by: Tom Vaidyan | August 24, 2007 10:31 AM
A side note - posted by a user on Adobe.com:
animagics said on Jul 23, 2007 at 9:06 AM :
This DOESN'T WORK unless you add FlashVars to the Javascript part of the HTML as well.
Find the "AC_FL_RunContent" function and add the following line to the middle of the list of parameters:
'FlashVars', 'myURL=http://weblogs.adobe.com/',
Posted by: Kyle | September 3, 2007 11:14 AM
Yes, it does help saving some time from looking up... :D
Posted by: Onanga | September 11, 2007 06:42 AM
tnx Onanga
didn't know that it has to be in JS
Posted by: web design | September 12, 2007 05:40 PM
Thanks mate! Saved my day.
Posted by: Thomas | December 5, 2007 08:17 AM
I have used your addChild method. But I can't use it in for loop.
Can you tell me how can I use multiple addChild using for loop?
I mean I want to use multiple attachmovie method using for loop, like as 2.
==============================
//AS 2 Method
for(var int:i=0;i
var btn:MovieClip=cont.attachMovie("library instance name","new name"+i,level)
btn._x=i*30
}
how can I use this method in as 3 ????
Posted by: Arindam Mojumder | December 7, 2007 09:56 PM
It can be a little simpler than this... in your document class you can use code like so... note that with the present Flash Published HTML page you do not have to touch the JavaScript to use FlashVars - just add it to the list of parameters on the HTML page and it works fine.
package {
import flash.text.TextField;
import flash.display.Sprite;
import flash.display.LoaderInfo;
public class Viewer extends Sprite {
public function Viewer() {
var myText:TextField = new TextField();
// this assumes that you are going to pass in an id variable
// on the end of the myFile.swf?id=12345 or
// use FlashVars in the HTML parameter list for instance
// 'FlashVars', 'id=123456', 'width', '1024',
myText.text = String(loaderInfo.parameters.id);
addChild(myText);
}
}
}
Posted by: Dan Zen | December 11, 2007 09:53 PM
I was having trouble with this until I read in another post that in order for this to work the DisplayObject needs to be added to the displayList first.
Posted by: Kevin | December 17, 2007 06:06 AM
Please can you help me with this in AS 2.0?
I want to create from the FLA the code to create a paramter to receive values from a URL.
Can you show me an example?
Thanks a lot!
Posted by: Christian | January 9, 2008 11:28 AM
Would you mind editing the original post to include the bit about the AC_FL_RunContent needing the FlashVars as well? That's pretty important to know, and easy to miss since it's way down in the comment list. (I didn't see it until after I'd figured it out.)
Posted by: Solomon | January 19, 2008 04:14 PM
I'd second adding the AC_FL_RunContent stuff. I just spent about an hour figuring it out, after I'd read your initial post, after doing some grindign to convince myself that object really WAS null, and checking for the 12th time that both the embed and param tags were OK, I finally read thru the entire generated HTML.
All that stuff down there only gets called if we're in land. 8c(
Posted by: annie | February 13, 2008 01:03 PM
I get an error: 1067: Implicit coercion of a value of type Error to an unrelated type String. And when i cast the error into a String, it casts whatever is in parameters into the empty string.
Posted by: doesntwork | February 25, 2008 03:07 AM
Oops, it looks like I had a bug in the original code.
I changed the "tf.appendText(error)" to "tf.appendText(error.toString())" and now it *should* work.
Sorry, and thanks for pointing it out,
Peter
Posted by: peterd | February 25, 2008 11:10 AM
Thank you so much for this tutorial.
Posted by: web design | flash web design | March 2, 2008 10:44 PM
Thanks, this saved me hours of experimenting!
Posted by: Ted | April 3, 2008 09:31 AM
Also, you can easily access passed in parameters like so...
var varName:String = loaderInfo.parameters.passedInParam;
Posted by: matt | April 16, 2008 01:08 PM
Hi, I've been trying to use query string and php..
" />
$a value is 1, but the flash returns me the whole value which is ``.
I've searched in the internet and found out in AS2 the code will return the correct output which is 1.
Can AS3 do this or i should switch to AS2?
Posted by: Andy Edward | April 17, 2008 02:03 AM
Yes, the value is 1 and the flash returns the whole value.
I believe you should switch to as2
Posted by: Professional Web Design | Flash Developer | Web Design Romania | Flash Web Design | Professional Web | May 12, 2008 09:18 AM
dude, just passing on my thanks. cheers.
Posted by: ask | May 26, 2008 10:57 AM
I have found that used with swfobject 2.0 from svn with all javascript in the html head, the flash var is not populated imediately, see extract below for a possible solution
private function processLoadVars():
{
_timer = new Timer(40,0);
_timer.addEventListener( TimerEvent.Timer, isReady );
_timer.start();
}
private function isReady()
{
_allFlashVars = Loader( _level0.loaderInfo ).parameters;
var notEmpty:Boolean = false;
for( var all in _allFlashVars )
{
notEmpty = true;
break;
}
if( notEmpty )
{
_timer.stop();
loadflashvarReady();
}
}
This code also stops flash throwing an error when running the swf.
Cheers
Justin
Posted by: JLM | June 5, 2008 05:19 AM
I have found that used with swfobject 2.0 from svn with all javascript in the html head, the flash var is not populated imediately, see extract below for a possible solution
private function processLoadVars():
{
_timer = new Timer(40,0);
_timer.addEventListener( TimerEvent.Timer, isReady );
_timer.start();
}
private function isReady()
{
_allFlashVars = Loader( _level0.loaderInfo ).parameters;
var notEmpty:Boolean = false;
for( var all in _allFlashVars )
{
notEmpty = true;
break;
}
if( notEmpty )
{
_timer.stop();
loadflashvarReady();
}
}
This code also stops flash throwing an error when running the swf.
Cheers
Justin
Posted by: JLM | June 5, 2008 05:19 AM