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:

&lt!-- 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.

58 Responses to Using FlashVars with ActionScript 3.0

  1. JOsH says:

    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.

  2. JOsH says:

    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.

  3. Dan Zeitman says:

    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?

  4. Tracy says:

    Hi thereUseful 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;

  5. Patrick says:

    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

  6. 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

  7. How do you do this with the SDK, without timeline access, the above does not work.Thanks,Patrick

  8. Gabriel says:

    How to get flash var values with FLEX and AS3:http://www.abdulqabiz.com/blog/archives/macromedia_flex/how_to_get_url.phpBasically,mx.core.Application.application.parameters.nameWhere “name” is the name of the flashvar. So for the example of this page:mx.core.Application.application.parameters.onemx.core.Application.application.parameters.two

  9. Deborah Thomas says:

    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.

  10. Sam says:

    Thanks. Always nice to google and get a working recipe as the first link.

  11. Justin says:

    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.

  12. Thanks, this helped a lot!

  13. michael says:

    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

  14. Marc says:

    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?

  15. Peter says:

    Marc,Can you clarify what you mean by “unless I access the page remotely”?Peter

  16. Marek says:

    Self-made recovery: flash content should be fully loaded before attempting to access variables. Preloading solves the problem.

  17. lisamarienyc says:

    Thanks, Peter! Saved me valuable time, and worked like a charm. :)

  18. That is exactly what I was looking for. Thanks!

  19. In Flex 2.0 it is slightly different:package {//dependenciesimport 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);}}}}

  20. Tom Vaidyan says:

    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.

  21. Kyle says:

    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/’,

  22. Onanga says:

    Yes, it does help saving some time from looking up… :D

  23. web design says:

    tnx Onangadidn’t know that it has to be in JS

  24. Thomas says:

    Thanks mate! Saved my day.

  25. Arindam Mojumder says:

    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 Methodfor(var int:i=0;i

  26. Dan Zen says:

    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);}}}

  27. Kevin says:

    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.

  28. Christian says:

    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!

  29. Solomon says:

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

  30. annie says:

    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(

  31. doesntwork says:

    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.

  32. peterd says:

    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

  33. Thank you so much for this tutorial.

  34. Ted says:

    Thanks, this saved me hours of experimenting!

  35. matt says:

    Also, you can easily access passed in parameters like so…var varName:String = loaderInfo.parameters.passedInParam;

  36. Andy Edward says:

    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?

  37. Yes, the value is 1 and the flash returns the whole value.I believe you should switch to as2

  38. ask says:

    dude, just passing on my thanks. cheers.

  39. JLM says:

    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 solutionprivate 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.CheersJustin

  40. JLM says:

    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 solutionprivate 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.CheersJustin

  41. Shad says:

    Why use AS3 rather than AS2?

  42. Lucas says:

    Hello, im Lucas from Argentina. Sorry for my poor english!! :)I have a problem with FlashVars. In this example you put the text in the parameters (one=1&two=2). How can I do if I want to get the text of the parameters from a textfield in the html page instead of write it with the keyboard?I mean to make something like:param name=”FlashVars” value=”one=” + txtPar1.value + “&two=” + txtPar2.valueI have tried this, but i get an error. Can you help me?Thanks a lot! And sorry for the mistakes in the text!

  43. idflood says:

    Thanks, it saved me some time : )Shad : I think you will have to go for some javascript.- wait for the page to load- get the value of txtPar1.value, …- And only then embbed the swf with something like swfobject ( http://blog.deconcept.com/swfobject/ )I would also recommend using some javascript framework to make it more easy to developp ( jquery, mootools, …)JLM: Hmm lot’s of great changes are in as3 ( faster, better coding standards, …) This is exactly the same reason why we don’t make any site in html1.0 nowaday ; )

  44. Sharath says:

    Doesn’t work unless we use include FlashVars in AC_FL_RunContent.I had tough time figuring this out since I had not read the comments earlier.Please update the post to mention the FlashVars that need to be passed along with AC_FL_RunContent function call in Javascript.

  45. ThomasA says:

    Thanks! That saved me 10 minutes.

  46. Sargento says:

    Thanks for this doc.BTW:I just needed to grab one of the variables sent via FlashVars and used this:var myVar:String = LoaderInfo( this.root.loaderInfo ).parameters.flashVarName;Hope this helps someone.Thanks and Best Regards.

  47. Robert says:

    I’ve never in my life gotten this to work. I’m trying it now in Flash CS3 and it doesn’t work.

  48. OleDid says:

    Thanx mate ;) You saved me more than 3 minutes searching, that’s for sure :D

  49. Keeler says:

    Hmm.. I have tried duplicating this code exactly as written (while making sure that my .swf file is named main.swf as well) and cannot get it to display the variables.Is there something you must change in the code that isn’t mentioned?

  50. Matt says:

    Thanks! This was helpful and straightforward, unlike some of the other sites I found.

  51. Manfred says:

    Hi thereAs many others, I am extremely thankful for this script. It is precisely what I needed. Thanks.I am however wondering about the embedding. I changed the pluginspage parameter to http://get.adobe.com/flashplayer/, but how about the codebase? For the moment http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab is still working, but that might be moved to adobe too.What do you recommend?CheerioManfred

  52. Mikkel says:

    awesome, thanks for sharing all this info. Just made my day.

  53. Atif says:

    Hi therereally nice work… thanks a lot.I would like to add that those of you who are not able to still run it successfully(like oledid), remove tag from your html page. After removing tag you can easily pass variable values using query string.CheersAtif

  54. Andy See says:

    Thanks this is very helpful, but how can I pass Flashvars to a swf I want to laod from within my swf.

  55. Paul says:

    Ok here’s a tricky one. How do you get the flash vars that are passed into a parent swf from a loaded swf file, if you are working in a pure as3 project. I.e. not flash or flex. Obivously root doesn’t work, and because its not flex the mx.core libraries aren’t available. This is the current hack we had to put together:public static function getLoaderInfo(dispObj:DisplayObject):LoaderInfo {var root:DisplayObject = getRootDisplayObject(dispObj);if (root!=null) {return root.loaderInfo;}return null;}public static function getRootDisplayObject(dispObj:DisplayObject):DisplayObject {if (topParent==undefined) {if (dispObj.parent!=null) {return getRootDisplayObject(dispObj.parent);} else {topParent = dispObj;return topParent;}} else {return topParent;}}As you can see its a pretty nasty loop all the way up the display stack till you hit the null parent object, which should be the swf file that has been loaded and passed the flashvars. Any ideas on a more elegant solution?

  56. Kawika says:

    It worked. Thanks! Just what I needed.

  57. clay says:

    I’m actually looking to insert loaderInfo into a loaded swf from a swf.

    Maybe I’m overlooking something much simpler?