Best way to get address variables into Flash

I’ve seen too many wrong or old soulotions for sending query string variables into Flash (page.html?var1=Jon&var2=Smith… etc.). In fact, if you’ll google it you’ll find this old Macromedia article from the year 2000 and about Flash 4, while most of it still applies it’s definitely old. These days, we’re using swfobject, if you don’t use it then you should, swfobject comes with a “global” javascript function called getQueryParamValue and you can use it for setting query/address string variables into FlashVars as follows:

[js]var so = new SWFObject(“movie.swf”, “flashMovie”, “250”, “150”, “8”, “#FFFFFF”);
so.addVariable(“var1”, getQueryParamValue(“var1”));
so.addVariable(“var2”, getQueryParamValue(“var2”));[/js]

These variables will be availble as root.var1, _root.var2, etc. For complete explanation go here. The best thing about FlashVars is that they are available for use as soon as the Flash movie starts, and before everything else, so you can refer, for example, to the variable *root.var1* in the first line of code, as opposed to another old method setVariable, where we had to wait for the variable availability using somthing like watch.

Though the advantage of FlashVars, personly, I don’t like _root variables, it seems unclean, especially when it’s a long query string that’ll make tons of them floating in my _root. Since Flash 8 we can use ExternalInterface to call to *getQueryParamValue *and get an immediate and synchronous response from within Flash, that way we can have a neater control over owr address variables, for example:

[as]var sVar1:Object = ExternalInterface.call(“getQueryParamValue”, “var1”);[/as]

Play with the example, try different variables.

If you don’t use swfobject, I guess you can easily write your own javascript method for getting address variables, but why bother, I don’t think you can easily improve on that one. I also don’t think that Geoff Stearns, the author of swfobject, will care if you’ll copy this function:

[js]function getQueryParamValue(param){
var q = document.location.search || document.location.hash; if(q){
var startIndex = q.indexOf(param +”=”);
var endIndex = (q.indexOf(“&”, startIndex) > -1) ? q.indexOf(“&”, startIndex) : q.length;
if (q.length > 1 && startIndex > -1) {
return q.substring(q.indexOf(“=”, startIndex)+1, endIndex);
}
}
return “”;
}[/js]

It’s great for non flash websites as well.

Get example files

Get swfobject

Guy A

Read more posts by this author.