Actionscript 3.0, Flash, Flex, Web developer

Actionscript Snippets : Get Flashvars in AS3

I am starting here a new series of posts, an Actionscript snippets that are useful in everyday programming. This is mainly because I don’t have time to share full source codes and examples, but I will try to find it. Until then I will post codes that are small but useful.

Let’s start with getting a Flashvars in AS3, something we often need to do

private function getFlashVars():Object {
	return Object( LoaderInfo( this.loaderInfo ).parameters );
}

remove private from function if you code in Flash IDE, but I hope you are into OOP thing.
After this retrieving of Flashvar is easy

_var1 = getFlashVars().var1;  // var1 is the name of the passed Flash variable

watch out, if var1 is not passed value returned will be undefined, so you can use like Ian Kirk said, but watch out for passing 0 value as Flash var then…

_var1 = getFlashVars().var1 || "defaulValue";  // var1 is the name of the passed Flash variable
About these ads
Standard

16 thoughts on “Actionscript Snippets : Get Flashvars in AS3

  1. Great idea to do a snippets series. I have found recently that testing Flash developments that use FlashVars can get pretty annoying if after publishing from Flash IDE you have to go into the html and put the variables there every time.

    Here’s a tip to build on the tip that you gave. Change the code to retrieve _var1 as follows:

    _var1 = getFlashVars().var1 || “testvalue”;

    The || is an OR like you normally see in ‘if’ statements.

    When you are testing, getFlashVars().var might be null because the FlashVars aren’t set in the html. Using the code above, _var1 will pick up “testvalue” (or whatever you choose) as its default instead.

    That way you can avoid compiler errors whilst you’re working on testing that might arise if _var1 was set to ‘null’ because the html hadn’t got the flashvars set up in it yet.

    This tip saved hours on a production project where the html was another developer’s responsibility, letting us each work in parallel in our own development environments for stretches of time and reducing interdependency in our work until it was time for larger-scale testing.

  2. Pingback: Video | Enjolt.com | Innovate for Success

  3. Thanks! Tried a few tutorials on this, all using much more complicated code that didnt work! This worked great for me and will be bookmarking your site for sure

  4. Thanks! Your solution was the first one between lots of tutorials about Flashvars transitioning from the usual getURL(var) at AS2 to a simple AS3 solution that worked! Most tutorials were overkill considering what I needed.

    My code ended like this:

    function getFlashVars():Object {
    return Object( LoaderInfo( this.loaderInfo ).parameters );
    }

    var url = getFlashVars().name_of_var;

    //button calls url

    btn.addEventListener(MouseEvent.CLICK, gotoURL)
    function gotoURL(e):void {
    navigateToURL (new URLRequest (“http://www.mysite.com/”+url))
    }

    Thanks again!

  5. timtom says:

    Need it to actually work in Flash CS4, i.e. flash player 10?

    var myTextField = new TextField();
    myTextField.appendText(“and: ” + String(LoaderInfo(this.root.loaderInfo).parameters["myFlashVariable"]) );
    myTextField.width = 200;
    myTextField.height = 40;
    myTextField.border = true;
    addChild(myTextField);

    in HTML, add PARAM tag and EMBED attribute: FlashVar=”myFlashVariable=blah blah blah”

  6. mel_06 says:

    hi timton,

    from the last example you did (myTextField ), how can i use that for playing a video or flv file?

    my video file will be coming from the PARAM tag and EMBED attribute in HTML.

  7. Pingback: How to use flashvars in as3 | CodeAngInaMo

  8. jung says:

    help me please..
    I want to insert FlashVar function as below codes.

    ======================================================
    /*
    *************************************
    * Flash CS3 CountDown – supported by PHP and XML
    * http://www.FlepStudio.org
    * © Author: Filippo Lughi
    * version 1.0
    *************************************
    */
    package org.FlepStudio
    {
    import flash.display.*;
    import flash.events.*;
    import flash.text.*;
    import flash.net.*;
    import flash.utils.*
    import flash.xml.*;

    public class Main extends MovieClip
    {
    private var request:URLRequest=new URLRequest(“set_up.xml”);

    private var yearToExpire:int;
    private var monthToExpire:int;
    private var dayToExpire:int;
    private var hourToExpire:int;
    private var minutesToExpire:int;
    private var secondsToExpire:int;
    private var timeZoneHours:int;
    private var timeZoneMinutes:int;
    private var serverTime:int;
    private var serverDateSeconds:Number;
    private var eventDateSeconds:Number;

    private var expiredText:String;
    private var PHPurl:String;

    private var eventDate:Date;

    private var timer:Timer;

    private var expired_txt:TextField;

    public function Main()
    {
    addEventListener(Event.ADDED_TO_STAGE,init);
    }

    private function init(evt:Event):void
    {
    removeEventListener(Event.ADDED_TO_STAGE,init);

    loadXML();
    }

    private function loadXML():void
    {
    var loader:URLLoader=new URLLoader();
    loader.addEventListener(Event.COMPLETE,completeHandler);

    try
    {
    loader.load(request);
    }
    catch(error:Error)
    {
    trace(‘Impossibile caricare il documento.’);
    }
    }

    private function completeHandler(event:Event):void
    {
    var result:XML=new XML(event.target.data);
    var myXML:XMLDocument=new XMLDocument();
    myXML.ignoreWhite=true;
    myXML.parseXML(result.toXMLString());
    var node:XMLNode=myXML.firstChild;
    var n:int=int(node.childNodes.length);
    for(var i:int=0;i<n;i++)
    {
    if(i==0)
    yearToExpire=int(node.childNodes[i].firstChild.nodeValue);
    if(i==1)
    monthToExpire=int(node.childNodes[i].firstChild.nodeValue);
    if(i==2)
    dayToExpire=int(node.childNodes[i].firstChild.nodeValue);
    if(i==3)
    hourToExpire=int(node.childNodes[i].firstChild.nodeValue);
    if(i==4)
    minutesToExpire=int(node.childNodes[i].firstChild.nodeValue);
    if(i==5)
    secondsToExpire=int(node.childNodes[i].firstChild.nodeValue);
    if(i==6)
    timeZoneHours=int(node.childNodes[i].firstChild.nodeValue);
    if(i==7)
    timeZoneMinutes=int(node.childNodes[i].firstChild.nodeValue);
    if(i==8)
    expiredText=node.childNodes[i].firstChild.nodeValue;
    if(i==9)
    PHPurl=node.childNodes[i].firstChild.nodeValue;
    }

    getServerTime();
    }

    private function getServerTime():void
    {
    eventDate=new Date(yearToExpire,monthToExpire-1,dayToExpire,hourToExpire,minutesToExpire,secondsToExpire);

    var richiesta:URLRequest=new URLRequest();
    richiesta.url=PHPurl;
    var loader:URLLoader=new URLLoader();
    addListeners(loader);
    try
    {
    loader.load(richiesta);
    }
    catch (error:Error)
    {
    trace('Unable to load richiestaed document.');
    }
    }

    private function addListeners(d:IEventDispatcher):void
    {
    d.addEventListener(Event.COMPLETE,completato);
    }

    private function completato(e:Event):void
    {
    var loader:URLLoader=URLLoader(e.target);
    var vars:URLVariables=new URLVariables(loader.data);
    serverTime=vars.time;
    var server_milliseconds:Number=serverTime*1000;
    var b:Date=new Date();
    var offsetPC:Number=b.getTimezoneOffset()*60*1000;
    var real:Number=server_milliseconds+offsetPC;

    serverDateSeconds=real+timeZoneHours*60*60*1000+timeZoneMinutes*60*1000;
    eventDateSeconds=eventDate.getTime();

    startCountDown();
    }

    private function startCountDown():void
    {
    timer=new Timer(1000,0);
    timer.addEventListener(TimerEvent.TIMER,goCountDown);
    timer.start();
    }

    private function goCountDown(evt:TimerEvent):void
    {
    serverDateSeconds+=1000;
    var countDown:Number=(eventDateSeconds-serverDateSeconds)/1000;

    if(countDown<=0)
    {
    timer.stop();

    container_mc.alpha=0;

    showExpired();
    }

    var minutes:Number=Math.floor(countDown/60);
    var hours:Number=Math.floor(minutes/60);
    var days:Number=Math.floor(hours/24);
    countDown=(countDown%60);
    minutes=(minutes%60);
    hours=(hours%24);

    container_mc.day_mc.field_txt.text=days.toString();
    container_mc.hour_mc.field_txt.text=hours.toString();
    container_mc.minute_mc.field_txt.text=minutes.toString();
    container_mc.second_mc.field_txt.text=countDown.toString();
    }

    private function showExpired():void
    {
    expired_txt=new TextField();
    expired_txt.selectable=false;
    expired_txt.multiline=false;
    expired_txt.embedFonts=true;
    expired_txt.defaultTextFormat=getFormat();
    expired_txt.text=expiredText;
    expired_txt.width=expired_txt.textWidth+10;
    expired_txt.x=stage.stageWidth/2-expired_txt.width/2;
    addChild(expired_txt);
    }

    private function getFormat():TextFormat
    {
    var format:TextFormat=new TextFormat();
    format=new TextFormat();
    format.font="BadaBoom BB";
    format.color=0xFF9900;
    format.size=80;
    format.align=TextFormatAlign.CENTER;
    return(format);
    }
    }
    }

  9. My brother recommended I might like this website. He was once entirely right.
    This publish actually made my day. You cann’t imagine just how so much
    time I had spent for this information! Thanks!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s