Home Contact RSS

Get Current URL and Query String Parameters to Flash | Tutorial

1 Star2 Stars3 Stars4 Stars5 Stars (4 votes, average: 5 out of 5)
Loading ... Loading ...

Overview

This tutorial / how to / example will show how to get the current url from the browser to flash, and even how to get the query string parameters from the url into actionscript using ExternalInterface.
It has been a dilemma for many people to get this information into flash across browsers and without having to rely on flashvars or javascript, but to just have it work.
I wrote a post on it earlier, although it seemed it wouldn’t play nice with Internet Explorer IE, I later realized that it was only because of the way my blog is configured to embed flash. The call ExternalInterface.call(”window.location.href.toString”); or even ExternalInterface.call(’eval’, ‘window.location.href’); which basically do the same thing.
This can be taken even further and we can read the query string, which, if you don’t know what that is, is the data contained in the url. The data is sent as paired strings, the key and the value. So, for example I could have a url http://example.com/index.html?var1=one&var2=two&var3=three. The question mark separates the actual url path from the query string. So following the ‘?’ we see three variables: var1, var2 and var3, and their corresponding values: one, two and three. They are seperated as pairs with an ampersand (&) and then the key and value are seperated by an equals sign (=). So it goes url?key=value&key=value&key=value…
Once we pass the complete url into our swf, it’s pretty easy to parse the keys and corresponding values.

Steps

  1. Rather than use url with ExternalInterface.call(”window.location.href.toString”); implement the QueryString class make a new QueryString This will do most of the work for you: var myPath:QueryString = new QueryString();
    1. Upon creation of the QueryString object the class reads the parameters automatically by parsing the parameters after the ‘?’ and delimiting on the ‘&’. So you get var1=one and var2=two
    2. Set up each parameter (key) as a variable in the parameter object of the QueryString class assigning it’s value to that variable.
  2. Access your values as myPath.parameters.var1 and myPath.parameters.var2
  3. unescape() your values to make the usable, unless you need them to be encoded or course. Unescape decodes the string from URL-encoded format (converting all hexadecimal sequences to ASCII characters). If your parameter had been some funky encoded string like var4=this+stuff%3E%22%28%29%3F, after you unescape(myPath.parameters.var4) you get: this stuff>”()?.

Example

get url params screenshot
Here’s a working example. This link has the parameters appended to it following the question mark ‘?’ and separated with an ampersand ‘&’ like all query string parameters. I have one for myName (Circlecube) another for myText (Jo Jo is a monkey) which are both pulled out and put into their own text box after they are unescaped, and then there are a couple more parameters just to show, the aNum (3013), anotherParam (more), and ref (http://blog.circlecube.com/…)

Special thanks to Abdul Qabiz example. I rewrote it for as2 so it would work with some flash projects I’m working on.

I use the new swf object 2 to embed the swf. Go get it here: swfobject

Actionscript:

The actionscript layer of the swf

  1. import flash.external.*; //so we can use externalInterface
  2. import QueryString.as;   //so we can use the QueryString Class//make a new QueryString named myPath
  3. var myPath:QueryString = new QueryString();
  4. assignVariables();
  5.  
  6. //custom function to handle all the query string parameters
  7. function assignVariables() {
  8. //if myName parameter exists
  9. if (myPath.parameters.myName) {
  10. //assign it to the text of the myName text box
  11. //unescape() will translate/unencode the url characters
  12. myName.text = unescape(myPath.parameters.myName);
  13. }
  14. if (myPath.parameters.myText) {
  15. myText.text = unescape(myPath.parameters.myText);
  16. }
  17. if (myPath.url) {
  18. //get the complete url (including any parameters)
  19. thisUrl.text = myPath.url;
  20. }
  21. recurseTrace(myPath.parameters, " ");
  22. }
  23.  
  24. //function to recursivly print objects in heirarchy as string
  25. //so we get all parameters no matter what the key traced into
  26. //the allParams text box.
  27. function recurseTrace(info:Object, indent:String) {
  28. for (var i in info) {
  29. if (typeof info[i] == "object") {
  30. traceParams(indent + i + ":");
  31. recurseTrace(info[i], indent + " ");
  32. }
  33. else {
  34. traceParams(indent + i + ": " + info[i] + "\n");
  35. }
  36. }
  37. }
  38.  
  39. function traceParams(traceMe:String) {
  40. allParams.text += traceMe;
  41. }

The QueryString.as class for as2

  1. class QueryString {
  2. //instance variables
  3. var _queryString;
  4. var _all;
  5. var _params:Object;
  6.  
  7. public function QueryString() {
  8. readQueryString();
  9. }
  10. public function get getQueryString():String {
  11. return _queryString;
  12. }
  13. public function get url():String {
  14. return _all;
  15. }
  16. public function get parameters():Object {
  17. return _params;
  18. }
  19.  
  20. private function readQueryString() {
  21. _params = {};
  22. try  {
  23. _all = ExternalInterface.call("window.location.href.toString");
  24. _queryString = ExternalInterface.call("window.location.search.substring", 1);
  25. if(_queryString) {
  26. var allParams:Array = _queryString.split('&');
  27. //var length:uint = params.length;
  28.  
  29. for (var i = 0, index = -1; i < allParams.length; i++) {
  30. var keyValuePair:String = allParams[i];
  31. if((index = keyValuePair.indexOf("=")) > 0) {
  32. var paramKey:String = keyValuePair.substring(0,index);
  33. var paramValue:String = keyValuePair.substring(index+1);
  34. _params[paramKey] = paramValue;
  35. }
  36. }
  37. }
  38. }
  39. catch(e:Error) {
  40. trace("Some error occured. ExternalInterface doesn't work in Standalone player.");
  41. }
  42. }
  43. }

Download

Here’s a zip file containing the sample files, the QueryString Class file, and even the swfobject javascript file.
getURLParams.zip

Tags: , , , , , ,

Related posts

flashden banner

Gravatar

Manoj Patil said,

March 25, 2008 @ 7:03 am

I tried this and it does not working on IE 6.x :(

It works fine on firefox and opera…

Gravatar

Evan Mullins said,

March 25, 2008 @ 2:26 pm

Hmm… sorry about that, I didn’t have an IE6 around for testing… It works for me in IE7 though.

Gravatar

ammon said,

April 19, 2008 @ 6:51 am

Manoj, must be a problem with your implementation, works fine for me in IE 6.0

Gravatar

Evan Mullins said,

April 19, 2008 @ 9:03 am

Sweet, that’s good news. Thanks for sharing ammon!

Gravatar

Gustav said,

April 25, 2008 @ 2:34 pm

Looks promising! Does anyone know if this solution is affected by how “allowScriptAccess” is set in the embed/object tag?

Thanks for the effort by the way!

Gravatar

elastic said,

April 28, 2008 @ 4:05 pm

thank you so much for this post - it looks exactly like that i need to do. one problem on my machine - when i save the file, this stops working. maybe i should not save as CS3? it broke on both CS3 and flash 8…

Gravatar

elastic said,

April 28, 2008 @ 4:14 pm

nevermind first post, did something wrong (l left out the expressInstall attribute on the swfobject. :-) please disregard!!!

also, again, thanks for this awesome post.

Gravatar

elastic said,

April 29, 2008 @ 12:08 am

is safari compatible? i have this reading perfectly in both firefox and in opera, but safari acting weird. not setting the url.

Gravatar

elastic said,

April 29, 2008 @ 12:15 am

this is the best thing you did, and i appreciate it sooo much. i am having one weird problem- if i look at:

file:///Library/WebServer/Documents/mysite/getURLParams3.html?myName=harry&myText=knuckles

through my browser this works fine. if i look at it :

http://127.0.0.1/mysite/getURLParams3.html?myName= harry&myText=knuckles

this does not work in safari. however, both opera and firefox have no complaints.

maybe a swfobject / safari issue? but safari is OK with it to some degree :-S

Gravatar

Evan Mullins said,

April 29, 2008 @ 10:41 am

Thanks. I can’t take all the credit, Abdul Qabiz had a similar example for Flex.

A real testing scenario would be ideal: to see what browser supports this and any problems they have and so forth.
I’ve heard many reports, but none are all encompassing… I know it works in firefox and IE7, i’ve heard it works in IE6, safari and opera, but haven’t personally tested it. It seems to work for some people and not for others, so I’m guessing it just takes some troubleshooting…
I did have some trouble in IE at first, but then after I used swfobject it worked just fine, so that may be the problem in safari?
Please let us know what you come up with!

Gravatar

garrett said,

April 29, 2008 @ 6:30 pm

You saved me alot of time friend.

Thanks.

Gravatar

Ryan Mac said,

May 8, 2008 @ 4:17 pm

Hi Guys,

Just to let everyone know…please dont use this if you arent using swfobject.
It doesnt work. Dont even waist your time. Its been two long hours. Two very long hours.
Ramble ramble ramble…

Gravatar

Alex said,

May 13, 2008 @ 7:23 am

Hi. What you describe in the introduction to your article here seemed to be exactly what I was looking for, mainly because of this “It has been a dilemma for many people to get this information into flash across browsers and without having to rely on flashvars or javascript, but to just have it work.”. Well, thats exactly what i wanted to do, so I browsed through your code which seems very appropriate, and then I attempted to implement it. This is where things go wrong.

Step 1: I copied your code example into flash, and manually removed all of the line numbers that appeared on each even numbered space.

Step 2: I used the guideline of your example and imported flash.external.* on the first line of the first frame of my project. however, it seems that flash cs3 doesn’t like that, and i had to move that import line into the first line of the .as file, or else it would complain about not being able to use ExternalInterface.

Step 3: i removed some more of the formatting errors that occurred as a result of copying and pasting the code (it didnt recognize the greater and less than symbols properly, so i converted them by hand)

ok so all of that was really no big deal in the grand scheme of things, because after doing that the movie compiles with no flaws. BUT… i notice that the variables are still not being read at all. So i reviewed the instructions again.. and i realized my mistake: Thrown in at the end of the article, just before the actual code is the sentence “I use the new swf object 2 to embed the swf. Go get it here:”

now I start to think to myself, “wait, the swf is embedded with some form of container? what is the purpose of doing all of this if i’m going to have to embed the swf into a page anyhow?”. Then to my dismay as I read through the user comments, all the way down at the bottom i see the comment that was left by Ryan Mac, just before mine. Well… I can get over the frustration of the wasted time, thats not the issue, but the whole experience of trying to solve this problem, which landed me at this web site, and countless others before, and I’m sure countless more to come in search of the solution leaves me with 2 underlying questions and I would really appreciate it if someone could help me out here.

Question 1: I don’t embed my swf files at all, they are linked to directly, and I would prefer to keep it that way. When i pass a query string into an swf file, the first argument can be read very directly with no problems. Example: http://www.mysite.com/mymovie.swf?name=myname&playall=no
I can access the myname parameter just by saying:
myvar = myname;
that works with no problems every time, but i can never access the second parameter “playall”.
thats what lead me to this site… does ANYONE know how i can access all of the variables in the query string without embedding my object?

and question #2: What is the purpose of this script? I don’t understand why anyone would go through the trouble of making the parameters of the querystring itself accessible if you still have to embed the object into an html.

Is there something that I’m missing that makes it a bad idea to link to your swf files directly rather than embedding them into an html? Does it restrict me from using ANY method to access all of my querystring parameters beyond the first?

any answers to these questions would be extremely helpful, thanks in advance.

Gravatar

Evan Mullins said,

May 13, 2008 @ 12:44 pm

@Alex’s question “Is there something that I’m missing that makes it a bad idea to link to your swf files directly rather than embedding them into an html? ”
Please refer to the documentation of swfobject to see an extensive answer. Or read this enlightening article: A List Apart | Flash Embedding Cage Match

@Alex’s question “Does it restrict me from using ANY method to access all of my querystring parameters beyond the first?”

@Alex re: Example: http://www.mysite.com/mymovie.swf?name=myname&playall=no
Are you serving swf files in the browser? If so I understand the confusion around using swfobject to embed the file. There are ways to get the full path to the swf and extract the params at the end of the swf path… Permadi’s example and many more

Gravatar

Ricky said,

July 9, 2008 @ 12:40 am

Hi Evan Great Blog it has helped me heaps

I have a problem though. I cannot get the myName and myText fields to fill
The demo works fine but when place the swf from the download on my sever to test these two fields do not fill. the url and params fills fine.

Do you know any reason why this might be I have tried but have not worked it out?

Cheers Ricky

Gravatar

Ricky said,

July 10, 2008 @ 3:46 pm

I figured it out I just needed to change the labels on the text boxes they cannot be the same as the Varianle.

Daniel

RSS feed for comments on this post · TrackBack URI

Leave a Comment