AS3: QueryString

View Documentation
Download Class

UPDATE 11/20/08: I've updated the class to fix the issue roi outlined in the comments. The download now goes the the new version, 1.1.

I've posted before on retrieving FlashVars and how to do it in AS3. FlashVars is the suggested way of grabbing in variables from outside of Flash, but if it isn't an option and you are still using old school query strings, this class will help you in grabbing variables out of the query string.

The class looks like this:

Actionscript:
  1. package com.reintroducing.utils
  2. {
  3.     import flash.external.ExternalInterface;
  4.     import flash.utils.Dictionary;
  5.     import flash.utils.getQualifiedClassName;   
  6.    
  7.     /**
  8.      * Singleton used to grab data out of the query string.
  9.      *
  10.      * @author Matt Przybylski [http://www.reintroducing.com]
  11.      * @version 1.1
  12.      */
  13.     public class QueryString
  14.     {
  15. //- PRIVATE & PROTECTED VARIABLES -------------------------------------------------------------------------
  16.  
  17.         // singleton instance
  18.         private static var _instance:QueryString;
  19.         private static var _allowInstance:Boolean;
  20.        
  21.         private var _pairDict:Dictionary;
  22.         private var _url:String;
  23.         private var _pairs:Array;
  24.        
  25. //- PUBLIC & INTERNAL VARIABLES ---------------------------------------------------------------------------
  26.        
  27.        
  28.        
  29. //- CONSTRUCTOR -------------------------------------------------------------------------------------------
  30.    
  31.         // singleton instance of QueryString
  32.         public static function getInstance():QueryString
  33.         {
  34.             if (QueryString._instance == null)
  35.             {
  36.                 QueryString._allowInstance = true;
  37.                 QueryString._instance = new QueryString();
  38.                 QueryString._allowInstance = false;
  39.             }
  40.            
  41.             return QueryString._instance;
  42.         }
  43.        
  44.         public function QueryString()
  45.         {
  46.             this.parseValues();
  47.            
  48.             if (!QueryString._allowInstance)
  49.             {
  50.                 throw new Error("Error: Use QueryString.getInstance() instead of the new keyword.");
  51.             }
  52.         }
  53.        
  54. //- PRIVATE & PROTECTED METHODS ---------------------------------------------------------------------------
  55.        
  56.         private function parseValues():void
  57.         {
  58.             this._url = ExternalInterface.call("document.location.search.toString");
  59.             this._pairDict = new Dictionary(true);
  60.             this._pairs = this._url.split("?")[1].split("&");
  61.            
  62.             var pairName:String;
  63.             var pairValue:String;
  64.            
  65.             for (var i:int = 0; i <this._pairs.length; i++)
  66.             {
  67.                 pairName = this._pairs[i].split("=")[0];
  68.                 pairValue = this._pairs[i].split("=")[1];
  69.                
  70.                 this._pairDict[pairName] = pairValue;
  71.             }
  72.         }
  73.        
  74. //- PUBLIC & INTERNAL METHODS -----------------------------------------------------------------------------
  75.    
  76.         /**
  77.          * Returns the value of the specified query string parameter.
  78.          *
  79.          * @param $val A string identifying the parameter for whose value you want to retrieve
  80.          *
  81.          * @return String The value for the given parameter
  82.          */
  83.         public function getValue($val:String):String
  84.         {
  85.             if (this._pairDict[$val] == null)
  86.             {
  87.                 return "";
  88.             }
  89.             else
  90.             {
  91.                 return this._pairDict[$val];
  92.             }
  93.         }
  94.    
  95. //- EVENT HANDLERS ----------------------------------------------------------------------------------------
  96.    
  97.        
  98.    
  99. //- GETTERS & SETTERS -------------------------------------------------------------------------------------
  100.    
  101.        
  102.    
  103. //- HELPERS -----------------------------------------------------------------------------------------------
  104.    
  105.         public function toString():String
  106.         {
  107.             return getQualifiedClassName(this);
  108.         }
  109.    
  110. //- END CLASS ---------------------------------------------------------------------------------------------
  111.     }
  112. }

It is a singleton and has a very simple usage. Consider the URL http://www.reintroducing.com?var1=one&var2=two. To retrieve var1, you would do the following:

Actionscript:
  1. import com.reintroducing.utils.QueryString;
  2.  
  3. var qs:QueryString = QueryString.getInstance();
  4.  
  5. trace(qs.getValue("var1"));

The values always come back as strings so you could treat them any way you like from there-on-out.

If you found this post useful, please consider leaving a comment, subscribing to the feed, or making a small donation.

56 Comments

Top quality code

Nice class here Matt.

thanks, glad you like it

An idiot question but where I have to put the .as file to load it in flash?

you could put it in the folder where your FLA is (the whole folder structure together, com.reintroducing..etc) or you could set it as a global classpath in your Flash preferences

I was wondering if there was a way of passing a default value if no variable was present eg if:

http://www.reintroducing.com was sent with no variables you could set var1=one and var2=two as a default.

Andrew,
Certainly, but that is not what the class was made to do. If you want to have defaults you have to anticipate that in your code in AS and not actually through the query string or this class. You could, though, add a getter to this class for the pairs array and check to see if its length is greater than 0 which would mean there is a query string in the URL and if not then set the defaults in your app.

ok....for the life of me, how do we use this class?
I have added it in flash and setup its class path ok...

but how do we get the string to be evaluated into this class in the first place? How do we pass it the main url we want to evaluate?

Thanks

roi,
it will automatically take the current URL into account to gather the query string variables from. All you have to do is say QueryString.getInstance().getValue("valueNameHere"); and it will return the variable that goes with that value. Hope that helps.

off couse it does, lol I finally looked into the .as script itself and there it was the ExternalInterface.call (little evil ;) hiding away ) and after hunting down the meaning of a singleton class...and just as we speak....im able to refresh my page and my textField is filled with one of the test parameters ;)
Ok here your official thank you. Thank you. :)

Good class. :)

you're welcome, glad it helped :P

I've discovered a little bug with this script...

Lets say you are calling in 2 parameters from the url....

So you line them in in AS as

QueryString.getInstance().getValue("myDate");
QueryString.getInstance().getValue("myTitle");

if you do not supply the first var, which in this case is "myDate" and you supplied the "myTitle" only parameter, it will not be read in...if you comment out the first parameter mydate...myTitle would than show.....

Off course if all parameters are present to be read in, everything works fine....

thanks

[...] variables to not show, rather it just returns an empty string. You can get the update from the original post. AS3, query, QueryString, [...]

roi,
I just updated the class to fix your issue. It'll now return an empty string for any variables that don't exist in the query string. I didn't initially account for this because I figured people wouldn't try to call variables that don't exist, but that's my mistake as they may be coming from a script and some may be missing. good catch and thanks for pointing it out.

Hi, Thanks for sharing with us this elegant way of retrieving query strings from the URL. I have however found a couple of issues:

1. There's a runtime error in parseValues() when testing the swf off-line because obviously the query string does not exist. This exception should be trapped either with a catch or an if statement which checks for the existence of this._url

2. It does not work at all in IE7 where the SWF is embeded with swfObject 2.1 using the "static publishing" method of swfObject. I don't think this is an issue with the QueryString class but rather a known IE problem where the SWF is unable to communicate with the browser until activated by mouse click, but I thought it may be worth people knowing anyway.

Many thanks, Ant.

Ant,
Thanks for pointing those out. The IE7 thing is probably what you described. As for the first one, again as you pointed out, the class isn't meant to be used offline. I don't like using try/catch because it is slow and unnecessary in my opinion. I know the class works online which is what it is intended to do so there are other ways in your code you could account for that, one of which is my Environment class.

question...

I'm trying to do:

var qs:QueryString = QueryString.getInstance();

without any query strings in the URL but Flash keeps throwing errors and breaking the class because its saying a term is undefined. Can I check to see if there are no Query Strings and have flash do something else instead easily?

I am getting an error if the QueryString does not exist. I have downloaded the the latest version. It does not seem to be passing "" as mentioned above. Any help would be greatly appreciated.

Tony

tony,
can you please post your code? and are you getting the error in the flash player browser or in the IDE? thanks.

corban,
the error is occuring when tested inside of the IDE because there is no query string available until it is loaded on the net. to avoid this, you could use my Environment class (listed on this blog) to do a simple check of the isLive variable. I'd strongly suggest you take a look at that class and use it to test if the site is online or in the IDE, it has saved me a ton of headaches in the past year or so.

and my apologies for taking so long to answer that.

[...] 4、AS3: QueryString     一个单例类,用来获取URL地址后所带参数值对 http://evolve.reintroducing.com/2008/07/03/as3/as3-querystring/#more-141 [...]

How do you use this to store a url variable, in a variable for use in an if then situation.

My goal is to load different xml playlists based on what variable is in the url.

I have an .as that loads a xml playlist into a tileList in flash. I want this .as to first check the current URL in the browser and then load the correct playlist out of several xml files.

thanks

Mark,
you could do something like this:

Actionscript:
  1. if (QueryString.getInstance().getValue("varToLookFor") == "valueToMatch")
  2. {
  3.     // code to load whatever xml file here
  4. }
  5. else
  6. {
  7.     // code to load alternate xml file
  8. }

Hope that helps.

thanks for a quick responce. I am getting this error:

TypeError: Error #1009: Cannot access a property or method of a null object reference.
at com.reintroducing.utils::QueryString/parseValues()
at com.reintroducing.utils::QueryString()
at com.reintroducing.utils::QueryString$/getInstance()
at VideoPlaylist()

Any thoughts?

If you're testing this in the IDE it won't work because there is no QueryString actually present unless you are testing online and have provided an appropriate query string in the URL.

Woops. Pushing live did it. Works great.

Thanks for the great work, solved a problem Ive had for a while.

Glad I could help, Mark :P

I have a series of if elses that check for a variable named "var" using :

if (QueryString.getInstance().getValue("var") == "1")
{xmlLoader.load(new URLRequest("playlist.xml"));}

If the URL does not contain a variable named "var" it errors out the whole operation.

How would I tell it to first make sure there are variables before running the variable checks, or is there possibly another solution to this.
Thanks again.

is there an else statement that goes with that if? maybe you can handle the error to do something other than that with an else statement.

this brings up a good point though, i should probably provide some public methods for getting the values and other useful info. i'll have to implement that into the next iteration. thanks for the heads up.

What is the solution for gettiing this to work with IE7? Everything works fine with Safari and mac but in IE7 it doesnt seem to be executing the externalinterface commands.

Mark,
I'm personally not aware of such issues, but a quick Googling found this: http://readlist.com/lists/chattyfig.figleaf.com/flashcoders/3/19053.html

although i didn't read the whole thread, the answer may lie somewhere in there.

Hello there,

I think your super duper class won't help me but it's always good to ask. I want to create flash website with changing url.
Like here for instance:
http://www.koniorstudio.pl/

Would you point me a way how it's done ?

Thanks | Pozdro

Dominik

@Dominik: what you are after is called SWFAddress. You can find it here: http://www.asual.com/swfaddress/

by the way, i like your site alot, it is very nicely done. it's obvious you put a lot of time into it.

i wogule jest dobrze widziec ze polacy robiom dobrom prace.

(sorry, my Polish writing skills are minimal)

[...] 4、AS3: QueryString     一个单例类,用来获取URL地址后所带参数值对 http://evolve.reintroducing.com/2008/07/03/as3/as3-querystring/#more-141 [...]

[...] 4、AS3: QueryString 一个单例类,用来获取URL地址后所带参数值对 http://evolve.reintroducing.com/2008/07/03/as3/as3-querystring/#more-141 [...]

[...] 4、AS3: QueryString     一个单例类,用来获取URL地址后所带参数值对 http://evolve.reintroducing.com/ … erystring/#more-141 [...]

Thanks Matt!

This class was just what I was looking for. Much appreciated!

Doyle

[...] 4、AS3: QueryString     一个单例类,用来获取URL地址后所带参数值对 http://evolve.reintroducing.com/2008/07/03/as3/as3-querystring/#more-141 [...]

Hi there,

Great little utility thanks! Did you know however, you could replace your Dictionary with a URLVariables...

private function parseValues():void
{
this._url = ExternalInterface.call("document.location.search.toString");
this._pairs = this._url.split("?")[1];
this._vars = new URLVariables(this._pairs);
}

where this._vars is just an object containing all of your query parameters. e.g.

var v:URLVariables = new URLVariables("propa=wibble&propb=wobble");
trace(v); // returns 'propa=wibble&propb=wobble'
trace(v.propa); // returns 'wibble'
trace(v.propb); // returns 'wobble'

Job done! :-)

[...] QueryString     一个单例类,用来获取URL地址后所带参数值对http://evolve.reintroducing.com/2008/07/03/as3/as3-querystring/#more-1415、ActionScript 3 Contextual Menu Manager [...]

[...] 4、AS3: QueryString 一个单例类,用来获取URL地址后所带参数值对 http://evolve.reintroducing.com/2008/07/03/as3/as3-querystring/#more-141 [...]

[...] 4、AS3: QueryString     一个单例类,用来获取URL地址后所带参数值对 http://evolve.reintroducing.com/2008/07/03/as3/as3-querystring/#more-141 [...]

[...] 4、AS3: QueryString     一个单例类,用来获取URL地址后所带参数值对 http://evolve.reintroducing.com/2008/07/03/as3/as3-querystring/#more-141 5、ActionScript 3 Contextual Menu Manager Class         AS3关联菜单管理类 [...]

[...] 4、AS3: QueryString     一个单例类,用来获取URL地址后所带参数值对 http://evolve.reintroducing.com/ … erystring/#more-141 [...]

[...] 4、AS3: QueryString 一个单例类,用来获取URL地址后所带参数值对 http://evolve.reintroducing.com/2008/07/03/as3/as3-querystring/#more-141 [...]

Corban says that he error is occuring when tested inside of the IDE because there is no query string available until it is loaded on the net. to avoid this, you could use my Environment class (listed on this blog) to do a simple check of the isLive variable. I'd strongly suggest you take a look at that class and use it to test if the site is online or in the IDE, it has saved me a ton of headaches in the past year or so.and my apologies for taking so long to answer that,can anyone comment on this?

This doesn't work in Safari, specifically in the Facebook platform. Anyone else have the same issue?

Works fine in every other browser.

@neil: I have not worked much with the FB platform. What is the format at which the FB platform returns URLs in?

[...] QueryString     一个单例类,用来获取URL地址后所带参数值对http://evolve.reintroducing.com/2008/07/03/as3/as3-querystring/#more-1415、ActionScript 3 Contextual Menu Manager Class         [...]

posicionamiento web SEO | Posicionamiento web | Posicionamiento en buscadores: SEO y Posicionamiento Web buscadores. Consultoría de ... bit.ly/w1ZI2t 5:49 PM Dec 31st, 2011 ...scribe.twitter.com/Posicionate_Web/status/153291618659745793...

SEO | Posicionamiento web | Posicionamiento en buscadores: SEO y Posicionamiento Web buscadores. Consultoría de ... bit.ly/w1ZI2t 5:49 PM Dec 31st, 2011 ...scribe.twitter.com/Posicionate_Web/status/153291618659745793...

Leave a comment

(required)

(required)