Get Current URL and Query String Parameters to Flash | Tutorial

Update: please see the newer tut talking about getting the current url, query string vars and more with as3

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 (https://circlecube.com/circlecube/…)

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
[cc lang=”actionscript” tab_size=”2″ lines=”40″]
import flash.external.*; //so we can use externalInterface
import QueryString.as; //so we can use the QueryString Class//make a new QueryString named myPath
var myPath:QueryString = new QueryString();
assignVariables();

//custom function to handle all the query string parameters
function assignVariables() {
//if myName parameter exists
if (myPath.parameters.myName) {
//assign it to the text of the myName text box
//unescape() will translate/unencode the url characters
myName.text = unescape(myPath.parameters.myName);
}
if (myPath.parameters.myText) {
myText.text = unescape(myPath.parameters.myText);
}
if (myPath.url) {
//get the complete url (including any parameters)
thisUrl.text = myPath.url;
}
recurseTrace(myPath.parameters, ” “);
}

//function to recursivly print objects in heirarchy as string
//so we get all parameters no matter what the key traced into
//the allParams text box.
function recurseTrace(info:Object, indent:String) {
for (var i in info) {
if (typeof info[i] == “object”) {
traceParams(indent + i + “:”);
recurseTrace(info[i], indent + ” “);
}
else {
traceParams(indent + i + “: ” + info[i] + “\n”);
}
}
}

function traceParams(traceMe:String) {
allParams.text += traceMe;
}
[/cc]

The QueryString.as class for as2
[cc lang=”actionscript” tab_size=”2″ lines=”40″]
class QueryString {
//instance variables
var _queryString;
var _all;
var _params:Object;

public function QueryString() {
readQueryString();
}
public function get getQueryString():String {
return _queryString;
}
public function get url():String {
return _all;
}
public function get parameters():Object {
return _params;
}

private function readQueryString() {
_params = {};
try {
_all = ExternalInterface.call(“window.location.href.toString”);
_queryString = ExternalInterface.call(“window.location.search.substring”, 1);
if(_queryString) {
var allParams:Array = _queryString.split(‘&’);
//var length:uint = params.length;

for (var i = 0, index = -1; i < allParams.length; i++) {
var keyValuePair:String = allParams[i];
if((index = keyValuePair.indexOf(“=”)) > 0) {
var paramKey:String = keyValuePair.substring(0,index);
var paramValue:String = keyValuePair.substring(index+1);
_params[paramKey] = paramValue;
}
}
}
}
catch(e:Error) {
trace(“Some error occured. ExternalInterface doesn’t work in Standalone player.”);
}
}
}
[/cc]

Download

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

52 thoughts on “Get Current URL and Query String Parameters to Flash | Tutorial

  1. I tried this and it does not working on IE 6.x 🙁

    It works fine on firefox and opera…

  2. 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!

  3. 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…

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

    also, again, thanks for this awesome post.

  5. 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 :

    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

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

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

  8. 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…

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

  10. @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

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

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

    Daniel

  13. Very good, but I have some question.

    There is a way to pick up only 1 parameter of the URL, and not all the parameters?

    EX: I have .com?name=adriano&lastname=junior&y=584466&state=sp

    I just wanna the “y” parameter and not all.

    This can be done?

  14. Hi Evan,

    In which line I insert this, myPath.parameters.y.

    I try put in some lines that I thought that would certainly work but didn´t work.

    Thanks you for your help.

    and sorry about my English

  15. Hello,

    I could solve the problem of the Y, the solution was in front of my eyes.

    The problem of IE, I not using the “swf object 2”, I using the normal object and embed tag, it´s possible works on IE using the normal object and embed, or only works with “swf object 2”?

    there is an example?

    Thank you.

    And sorry about my english.

  16. Dear Author,

    My side not working in IE 6,7 , do you have solutions for this issue, thanks a lot!!!

    Sincerely
    Juliet

  17. Hi, Evan,

    Can you help me out??? I tested, I tried and it does not working on any IE 6.x, why? can you help me with a solution?

    Sincerely
    Juliet

  18. Same problem here with IE7. It works great with FF/opera.

    I tought it was only cause of the call so tried: ‘ExternalInterface.call(’eval’, ‘window.location.href’);’ but still remains the same.

    Someone please…

  19. I would really like to say a huge thanks to Evan Mullins i have been searching high and low for this solution for 2 days.And i got it here.A few pointers u actually do not need .you can still run perfectly.

    This is what i have done :

    import QueryString.as;
    var myPath:QueryString = new QueryString();
    var AlbumID = unescape(myPath.parameters.nom);
    // Chose which gallery to display according to the queryString Passed
    if ( AlbumID == “1”){
    _global.galleryNum = 0;
    }
    if ( AlbumID == “2”){
    _global.galleryNum = 1;
    }

    but of course u have to include the query string class provided.

    Once again really thanks for this wonderful post.

  20. THANKS!!!!
    Youre code works great for my needs. I’m trying to verify (via ASP) if a user name exists in a DB, and then return (via QueryString) the value to the swf. I’ve spended allmost 2 days looking for answers in many different forums but it have been frustrating. Apparently wath works for many other people (loaderInfo.parameters.myValue) doesn’t work for me. (Probably I have missed something… but I’ve downloaded examples… copy paste code…) and nothing.

    Finally…QueryString.as have done an exellent job!

    Thanks again

  21. This must be the best way to solve this, only theres a thing i cannot solve since like 10 hours of not standing even for bathroom. I have Windows Vista Home Premium, with IIS 7.0 and PHP 5.
    Now, im going crazy, i downloaded your example, i copied it to my server, wow it works perfectly (opera and IE 7 and 8).
    I came here not by loading url vars, i used to be able to do that, but somehow, now it doesnt work in IE 7 or 8.
    So i saw ur example and works.
    BUT WHAT IS DRIVING ME CRAZY, I DONT WANT TO DEAL WITH THIS ANYMORE PLEASE HELP!
    Listen, i have this localhost/site/getURLParams/ yor example, everything works. Then i copy all files to localhost/site AND IT DOESNT WORK!!
    Before this i just copied code bla bla, to make it for my propuses, but since no success i decided it to COPY files, they seem to work ONLY on your example folder, HOW IN EARTH THIS IS HAPPENING!?! Im about to suicide!! =(

    Does anyone have an issue like this?? i surrendered and tried just to copy files on anywhere else. Somehow they just work inside the original example folder, it doesnt matter if i copy all files to another folder!!!

    1. @Victor- Are you sure you’re including all the files? I’m not exactly sure what your question is, but it seems you are having trouble getting my example to work in your files? So just having it live on the server is keeping it from working? Could it be an issue with allowscriptaccess or a crossdomain.xml file?

  22. Thanks a ton for this. Worked like a charm right out of the box. Worked in Safari 4, FF3.5 (mac & PC) IE 7 & 8 etc, etc. I do have one questions which is more of a general AS question perhaps but anyway…

    When my swf gets the URL I use a switch statement to determine which button to highlight (the current page’s button). That works great but the issue is that unless the URL is EXACTLY the same as I’ve declared, it won’t work. I’m wondering if there’s a way to declare an open-ended string. i.e. when you are working with IP addresses you might say 192.168.1.% to signify any IP as long as it has those first numbers. or using * to signify any user etc. So whatever that’s called is what I’m looking for.

    I’m using wordpress and some of the URLs for sub-content get appended with query junk:
    so… “http://www.blah.com/site/photos/” works fine but “http://www.blah.com/site/photos/?album=1&gallery=5” does not. so basically I’m trying to say if URL == (“http://www.blah.com/site/photos/” + ANYTHING) then do what I say. (which is to keep that button highlighted). So how do I declare “ANYTHING” as a string possibility.

    Perhaps you covered this but I haven’t been able to find anything.

    thoughts? (and thanks again)

  23. @Design Guy – A quick suggestion – Try splitting the url as a string with the delimiter at ‘?’ and then try to run the first part through your switch statement.

  24. Evan,
    I could use some of your expertise. Take a look at this URL http://techeloquent.acrobat.com/testdelete/ I want the user information to be passed into the id field via the URL. Is this possible? Are you interested in helping? Its Adobe presenter creating a flash of a powerpoint then published out to Adobe Connect Pro. Each user is entering from a portal with their own unique URL and I don’t want them to have to type in their user information however I want to capture it to match up to their answers.

    Help please?

    1. @Ed – It looks like it should be pretty simple. I’m sure it is possible. It looks like you’d just need the name field exactly as it’s done in this example.

  25. awesome! this is a great post. i had been trying to figure out how to create deep linking within my flash site – this post really helped!. i added in creating a var that holds a value established by using parseInt(myquerystringvalue); which turns the string value into a numeric.
    thank you!

  26. Hello.. It didn’t work for me. I have downloaded the files and ran the index.html file. I could not enter the url since writing mode is disabled. Please help me out in this. This is really urgent.

    Thanks
    Nikhil

  27. Hi Evan, I’m making some tests but the source file by isn’t working.

    I’m trying to test it in AS3 but it won’t bring me the URL responses…

    sample file

    Thanks a lot and Happy new year!!

    1. @yuri – is that file still online? It’s not downloading for me. Did you end up solving this? Sorry for the delay, I’ve been snowed in this week! Let me know how it turned out

      1. Hi evan,

        I solved my problem, thanks for your attention… do you have anithing on SRT subtitles and AS3 for timeline animation?

        Best regards!!

        1. @Yuri – I don’t have anything about subtitles at this time, no, but I’ll add it to my list though.

          So what was it that helped you solve your problem with your urls?

  28. I had a friend of mine take a look at what I had done and he made some changes on my code so it would break up the parameters and make flash do what I needed!!

  29. function getParam(strname:String)
    {
    var url:String = ExternalInterface.call(“function(){ return window.location.href.toString();}”); // Gets URL from external Interface
    var searchstr:String = strname + “=”; //Creates the search String for Indexing
    var startindex:int = url.indexOf(searchstr,0); //Get the start index for extracting the variable
    if (startindex == -1) //Check Param name was found in Url String
    {
    return null; //If param wasn’t found return NULL
    }
    else //IF Param was found
    {
    startindex = startindex + searchstr.length; //Offset the start index for extracting the variable by the length of the param name and the ‘=’ sign
    var checker:int;
    checker = url.indexOf(“&”,startindex); //get location (if any) of next ‘&’ symbol
    if (checker == -1)
    {
    var endindex:int = url.length + 1; // if there is no ‘&’ symbol then set the end index value for extracting the variable to the end of the URL
    }
    else
    {
    endindex = checker – 1;//else set the end index for extracting the variable to the index of the next ‘&’ symbol and offset – 1
    }
    var variable:String = url.substring(startindex,endindex + 1);//create string for the return, this is made from a substring of the url using the start and end index’s obtained, this will return the variable.
    return variable;
    }
    }

    This is a wee function i wrote from my research, i am a complete noob to flash and self taught in vb.net, to use this function feed it the name of the param you want from the url and it will return the value as a string i.e
    http://www.testwebsite.example.html?name=BOB&id=144054

    Textfield.text = getparam(“name”)
    Textfiels.text = getparam(“id”)

    This is tested in AS3 – Chrome, Firefox and IE8
    I hope this helps someone out there as i know how hard this information was to find and get working 🙂

  30. Hi

    I am trying to do something similar… well I am not interested just in reading the url I want to update the url string probably without sending request to the server.
    the thing is… my page is suppose to load something… if that does not exist it loads something else that corresponds to another url. now I want to change the current url to the url that corresponds to the content.

    any idea how to do that or weather if it is possible or not?

    thanks

Comments are closed.