A Flash Developer Resource Site

Results 1 to 10 of 10

Thread: FlashVars: Here is a way to pass variables to flash via AS3

  1. #1
    Member
    Join Date
    Sep 2007
    Posts
    75

    FlashVars: Here is a way to pass variables to flash via AS3

    I have been doing a lot of searching and speaking to a lot of people about a way to pass the current URL to flash so that I can make a simple button go to the down position based upon what page the person is on. WOW, what a pain... lol

    Well, A pain no more. Here is a list of everything I have found. Hopefully it will help someone out there.

    First, you can use FlashVars in order to talk to Flash.

    You can use Flash Vars by simply either adding parameters to the movie parameter in the HTML for flash as such

    <param name="movie" value="main.swf?one=1&two=2" />
    <embed src="main.swf?one=1&two=2"

    Code:
    <!-- using query string -->
    <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
            codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0"
            width="550"
            height="400"
            align="middle"
            id="main">
        <param name="allowScriptAccess" value="sameDomain" />
        <param name="movie" value="main.swf?one=1&two=2" />
        <param name="quality" value="high" />
        <param name="bgcolor" value="#ffffff" />
        <embed src="main.swf?one=1&two=2"
               width="550"
               height="400"
               autostart="false"
               quality="high"
               bgcolor="#ffffff"
               name="main"
               align="middle"
               allowScriptAccess="sameDomain"
               type="application/x-shockwave-flash"
               pluginspage="http://www.macromedia.com/go/getflashplayer" />
    </object>
    OR

    creating an additional parameter name called FlashVars such as:

    <param name="FlashVars" value="one=1&two=2" />
    FlashVars="one=1&two=2" (for the embed statement)

    Code:
    <!-- using FlashVars -->
    <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
            codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0"
            width="550"
            height="400"
            align="middle"
            id="main">
        <param name="allowScriptAccess" value="sameDomain" />
        <param name="movie" value="main.swf" />
        <param name="quality" value="high" />
        <param name="bgcolor" value="#ffffff" />
        <param name="FlashVars" value="one=1&two=2" />
        <embed src="main.swf"
               width="550"
               height="400"
               autostart="false"
               quality="high"
               bgcolor="#ffffff"
               FlashVars="one=1&two=2"
               name="main"
               align="middle"
               allowScriptAccess="sameDomain"
               type="application/x-shockwave-flash"
               pluginspage="http://www.macromedia.com/go/getflashplayer" />
    </object>
    Okay, that was the easy part.

    The next thing you have to be able to do is retrieve this information that you have just passed in

    This was not so easy to find. Even when you do find it tutorials that explain it, they are not correct and they end up not working.

    You have to change a few items in order to get this to work.

    1. You have to add the following parameter to the AC_FL_RunContent Javascript on the HTML page generated by Flash: 'FlashVars', 'YourFlashVarParameterHere'

    Such As:
    Code:
    <script language="javascript">
    	if (AC_FL_RunContent == 0) {
    		alert("This page requires AC_RunActiveContent.js.");
    	} else {
    		AC_FL_RunContent(
    			'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0',
    			'width', '550',
    			'height', '400',
    			'src', 'flashvars',
    			'quality', 'high',
    			'pluginspage', 'http://www.macromedia.com/go/getflashplayer',
    			'align', 'middle',
    			'play', 'true',
    			'loop', 'true',
    			'scale', 'showall',
    			'wmode', 'window',
    			'devicefont', 'false',
    			'id', 'flashvars',
    			'bgcolor', '#ffffff',
    			'name', 'flashvars',
    			'menu', 'true',
    			'allowFullScreen', 'false',
    			'allowScriptAccess','sameDomain',
    			'movie', 'flashvars',
    			'FlashVars', 'flashvars',
    			'salign', ''
    			); //end AC code
    	}
    </script>
    2. For testing, enter the following actionscript into your Actions Layer on your main timeline.

    Code:
    // Reading the FlashVars from the page
    var tf:TextField = new TextField();
    tf.autoSize = TextFieldAutoSize.LEFT;
    tf.border = false;
    addChild(tf);
    
    tf.appendText("params" + "\n");
    try {
        var keyStr:String;
        var valueStr:String;
        var paramObj:Object = LoaderInfo(this.root.loaderInfo).parameters;
        for (keyStr in paramObj) {
            valueStr = String(paramObj[keyStr]);
            tf.appendText("\t" + keyStr + "\t" + valueStr + "\n");
        }
    } catch (error:Error) {
        tf.appendText("error");
    }
    The above code creates a textbox dynamically and outputs the flash variable to that text field.

    The following code is what I believe to be the actual item that collects the variable.

    Code:
       var paramObj:Object = LoaderInfo(this.root.loaderInfo).parameters;
    I hope this helps someone here like many people here have helped me.

    Wayne

  2. #2
    Junior Member
    Join Date
    Oct 2007
    Posts
    2

    Here's another way

    Here's another way on how to embed variables. You just do it in one place. The variable is called productAmount:



    <!--url's used in the movie-->
    <!--text used in the movie-->
    <!-- saved from url=(0013)about:internet -->
    <script language="javascript">
    if (AC_FL_RunContent == 0) {
    alert("This page requires AC_RunActiveContent.js.");
    } else {
    AC_FL_RunContent(
    'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0',
    'width', '124',
    'height', '332',
    'src', '/media/flash/product_sidePanel',
    'quality', 'high',
    'pluginspage', 'http://www.macromedia.com/go/getflashplayer',
    'align', 'middle',
    'play', 'true',
    'loop', 'true',
    'scale', 'showall',
    'wmode', 'window',
    'wmode', 'transparent',
    'devicefont', 'false',
    'id', 'product_sidePanel',
    'bgcolor', '#ffffff',
    'name', 'product_sidePanel',
    'menu', 'true',
    'allowFullScreen', 'false',
    'allowScriptAccess','sameDomain',
    'movie', '/media/flash/product_sidePanel?productAmount=3',
    'salign', ''
    ); //end AC code
    }
    </script>
    <noscript>
    <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="124" height="332" id="product_sidePanel" align="middle">
    <param name="allowScriptAccess" value="sameDomain" />
    <param name="allowFullScreen" value="false" />
    <param name="movie" value="/media/flash/product_sidePanel.swf" /><param name="wmode" value="transparent" /><param name="quality" value="high" /><param name="bgcolor" value="#ffffff" /> <embed src="/media/flash/product_sidePanel.swf" quality="high" bgcolor="#ffffff" width="124" height="332" name="product_sidePanel" align="middle" allowScriptAccess="sameDomain" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />
    </object>

    </noscript>

  3. #3
    Senior Member
    Join Date
    Oct 2003
    Posts
    1,354
    I think you would have to add the query string to the param and embed tags as before, just incase the user has scripts turned off for their browser.

    <param name="movie" value="/media/flash/product_sidePanel.swf?productAmount=3" />...

    <embed src="/media/flash/product_sidePanel.swf?productAmount=3"...

  4. #4
    Junior Member
    Join Date
    Oct 2007
    Posts
    2

    You're right

    Sorry, was too lazy to include the other parameters.

    J

  5. #5
    Junior Member
    Join Date
    May 2008
    Posts
    1

    Unhappy

    Wow... it looks like Wayne ('SpectacularStuf') has done a very thorough investigation of this topic; but, I'm new to Flash authoring and I am still not getting any results.

    Any chance of seeing more detail (like, how the .FLA itself is constructed)?

    Thanks !

  6. #6
    Member
    Join Date
    Sep 2007
    Posts
    75
    Unfortunately, this board only allows me a 300kb upload and the file is 668kb.

    I can give you the actionscript however. If you want the actual file, you will have to email me.

    Go to http://www.scrfix.com and utilize the contact form.

    The below code has ALL of my actionscript in it for detecting what webpage we are on and changing over buttons for fade effect etc. You may not need the rest of it. It is marked for what's what.

    Code:
    // Display FlashVar onto webpage to ensure we are
    // receiving it
    
    var tf:TextField = new TextField();
    tf.autoSize = TextFieldAutoSize.LEFT;
    tf.border = false;
    tf.x = 50;
    tf.y = 10;
    addChild(tf);
    
    /*
    // defining the header layout elements
    var header_lay = new Layout(header_mc);
    header_lay.elements = {
    	bg_mc:{left:true,right:true,top:true,bottom:true},
    	bg2_mc:{left:true,right:true,top:true,bottom:true},
    	lefty_mc:{left:true},
    	righty_mc:{right:true},
    	red_mc:{top:true,left:true,right:true}
    }
    header_lay.constrain(header_mc.width,header_mc.height);
    */
    
    // Detect the FlashVar from the webpage
    try {
        var keyStr:String;
        var valueStr:String;
        var paramObj:Object = LoaderInfo(this.root.loaderInfo).parameters;
        for (keyStr in paramObj) {
    		valueStr = String(paramObj[keyStr]);
    		if (keyStr.indexOf(".") != -1){
            keyStr = keyStr.substring(0, keyStr.indexOf(".")); //now it's "home"
            }
        }
    //	tf.appendText(keyStr);
    } catch (error:Error) {
    //    tf.appendText(error);
    }
    
    function handleMouse(evt:MouseEvent):void{
           if(evt.currentTarget == MovieClip(getChildByName(keyStr))){
    		//Do nothing
                    return;
    	}
    	else {
               var frameLabel = '';
               switch(evt.type){
                  case MouseEvent.MOUSE_OUT:
                    frameLabel = "out";
                    break;
                  case MouseEvent.MOUSE_OVER:
                    frameLabel="over";
                    break;
                  case MouseEvent.MOUSE_DOWN:
                    frameLabel="down";
                    break;
                  case MouseEvent.MOUSE_UP:
                    frameLabel="up";
                    break;
     
               }
        	   evt.currentTarget.gotoAndPlay(frameLabel);
    	}
    }
    
    //Add the button onto the stage
    var tl:MovieClip = this;
    var buttonA = ["home","about","services","specials","contact"];
    for (var i:int=0; i<buttonA.length; i++) {
    	var childButton:MovieClip = MovieClip(tl.getChildByName(buttonA[i]));
    	this[buttonA[i]].btf.text = buttonA[i].toUpperCase();
    	this[buttonA[i]].btf.autoSize = TextFieldAutoSize.CENTER
    	childButton.buttonMode = true;
    	childButton.addEventListener("mouseOver",handleMouse);
    	childButton.addEventListener("mouseOut",handleMouse);
    	childButton.addEventListener("mouseDown",handleMouse);
    	childButton.addEventListener("mouseUp",handleMouse);	
    }
    
    /////////////////////////////////////////////////
    //Detect the webpage we are currently on from the flashvars parameter.
    /////////////////////////////////////////////////
    
    function wpdetect() {
    	//var webpages:Array = ["home.php","about.php","services.php","specials.php","contact.php"];
    	//trace("webpages Array successfully loaded");
    //	var curpage:String = paramObj['currentPage'];
    switch(keyStr) {
    		case "home":
    		//home button in down position here
    		home.gotoAndStop("down");
    		trace("User is on the home page");
    		break;
    		
    		case "about":
    		//about button in down position here
    		about.gotoAndStop("down");
    		trace("User is on the about page");
    		break;
    		
    		case "services":
    		//services button in down position here
    		services.gotoAndStop("down");
    		trace("User is on the services page");
    		break;
    		
    		case "specials":
    		//specials button in down position here
    		specials.gotoAndStop("down");
    		trace("User is on the specials page");
    		break;
    		
    		case "contact":
    		//contact button in down position here
    		contact.gotoAndStop("down");
    		trace("User is on the contact page");
    		break;
    		
    		default:
    		trace("Webpage not found.  Update Case Statement.");
    		trace(keyStr);
    		}
    	}
    /////////////////////////////////////////////////
    
    //What webpage are we on?
    wpdetect();
    Hope it helps,

    Wayne

  7. #7
    Member
    Join Date
    Sep 2007
    Posts
    75
    Just in case it helps, I scrapped this project because I didn't like it however the effects are still there in case anyone wants them.

    Here is the effect working in full. It detects the page with PHP, using PHP it stores the page name in the javascript function for FlashVars and then talks to Flash with that JavaScript.

    http://www.spectacularstuff.com/scrfix/backup/home.php

    PHP "What page are we on" Function - Goes at the top of the php page above all else. (Doesn't really matter but it is easier to view that way)
    Code:
    <?php
    function curPageName() {
    $flashvar = substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1);
    $flashvar = urlencode($flashvar);
    return $flashvar;
    }
    ?>
    JavaScript "I am using Flash, please detect and talk to SWF File" - (Goes in between the HTML <head></head> tags on your PHP page
    Code:
    <script language="javascript">
    	if (AC_FL_RunContent == 0) {
    		alert("This page requires AC_RunActiveContent.js.");
    	} else {
    		AC_FL_RunContent(
    			'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0',
    			'width', '996px',
    			'height', '259px',
    			'src', 'header',
    			'quality', 'high',
    			'pluginspage', 'http://www.macromedia.com/go/getflashplayer',
    			'align', 'middle',
    			'play', 'true',
    			'loop', 'true',
    			'scale', 'noscale',
    			'wmode', 'window',
    			'devicefont', 'false',
    			'id', 'header',
    			'bgcolor', '#ffffff',
    			'name', 'header',
    			'menu', 'false',
    			'allowFullScreen', 'true',
    			'allowScriptAccess','sameDomain',
    			'movie', 'header',
    			'FlashVars', '<?php echo curPageName(); ?>',
    			'salign', 't'
    			); //end AC code
    	}
    	</script>
    <noscript>
    	// Provide alternate content for browsers that do not support scripting
    	// or for those that have scripting disabled.
      	This content requires the Adobe Flash Player.
      	<a href="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash">Download Adobe Flash Player</a>
    </noscript>
    Flash please read my FlashVars - (In the root of your flash file, create an action layer in the timeline. In the first frame on the timeline of that Action layer, place the following code)
    Code:
    // Display FlashVar onto webpage to ensure we are
    // receiving it
    var tf:TextField = new TextField();
    tf.autoSize = TextFieldAutoSize.LEFT;
    tf.border = false;
    tf.x = 50;
    tf.y = 10;
    addChild(tf);
    
    // Detect the FlashVar from the webpage
    try {
        var keyStr:String;
        var valueStr:String;
        var paramObj:Object = LoaderInfo(this.root.loaderInfo).parameters;
        for (keyStr in paramObj) {
    		valueStr = String(paramObj[keyStr]);
    		if (keyStr.indexOf(".") != -1){
            keyStr = keyStr.substring(0, keyStr.indexOf(".")); //now it's "home"
            }
        }
    //	tf.appendText(keyStr);
    } catch (error:Error) {
    //    tf.appendText(error);
    }
    All of the above code does is bring it to Flash and display inside of flash so that you can see that it is there. It is soley up to you to do something with it. I finally gave up because I didn't like the design of the website. I could not figure out or get help on make AS3 shrink with the webpages along with all of my content when someone resized the webpage. I searched for months. Plenty of AS2 tutorials out there but nothing user-friendly on AS3. I found some AS3 tutorials however you had to be a rocket scientist to understand them.

    I finally went with a 100% PHP Flex design in the end. You can check it out below. I am still in the middle of building it.
    Computer Repair Sarasota

    Hope it helps.

    Wayne
    Last edited by SpectacularStuf; 05-26-2008 at 02:12 AM.

  8. #8
    Junior Member
    Join Date
    Sep 2008
    Posts
    1
    SpectacularStuf,

    I’m AS3 impaired! I’ve worked with AS2 a bit, and need to update our maps. Your post was VERY helpful, here’s my problem. I need to pass a VAR to a Yahoo Map. I can pass the VAR I need using your post (which I have inserted into my Flash AS3 and now getting the text box), but I can seem to pass it to the Address (which is now “Chicago”). Can you suggest a method to replace Chicago with the string VARs I’m passing? Here’s the code:

    HTML:

    <object classid="clsid27CDB6E-AE6D-11cf-96B8-444553540000" codebase="https://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0" width="231" height="230">
    <param name="movie" value="../flash/Map-ThisLoan-245-001.swf?LCNaddress= Seattle">
    <param name="quality" value="high">
    <embed src="../flash/Map-ThisLoan-245-001.swf?LCNaddress= Seattle" quality="high" pluginspage="https://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="231" height="230"></embed>
    </object>

    Flash AS3:

    import com.yahoo.maps.api.YahooMap;
    import com.yahoo.maps.api.YahooMapEvent;
    import com.yahoo.maps.api.core.location.LatLon;
    import com.yahoo.maps.api.core.location.Address;
    import com.yahoo.maps.webservices.geocoder.GeocoderResult ;
    import com.yahoo.maps.webservices.geocoder.events.Geocode rEvent;
    import com.yahoo.maps.api.markers.SimpleMarker;
    import com.yahoo.maps.api.MapTypes;


    var appid:String = this.loaderInfo.parameters.MyAPI;

    var _address:Address;

    // create the new YahooMap object.
    var _map:YahooMap = new YahooMap();

    // listen for the MAP_INITIALIZE event from YahooMap
    _map.addEventListener(YahooMapEvent.MAP_INITIALIZE , onMapInit);

    // initialize the map, passing the app-id, width and height.
    _map.init(appid,myMap.width,myMap.height);

    // Reading the FlashVars from the page
    var tf:TextField = new TextField();
    addChild(tf);

    tf.appendText('_address' + "\n");
    try {
    var keyStr:String;
    var valueStr:String;
    var paramObj:Object = LoaderInfo(this.root.loaderInfo).parameters;
    for (keyStr in paramObj) {
    valueStr = String(paramObj[keyStr]);
    tf.appendText(valueStr + "\n");
    }
    } catch (error:Error) {
    tf.appendText("error");
    }


    function onMapInit(event:YahooMapEvent):void
    {
    _map.addPanControl();
    _map.addZoomWidget();

    // creating a new address object, passing our address string as the single parameter.
    _address = new Address("chicago");

    // listen for the GEOCODER_SUCCESS event dispatched when the data comes back from the webservice.
    _address.addEventListener(GeocoderEvent.GEOCODER_S UCCESS, handleGeocodeSuccess);

    // send the geocode request.
    _address.geocode();

    myMap.addChild(_map);
    }


    function handleGeocodeSuccess(event:GeocoderEvent):void
    {
    // retrieve the first result returned by the geocoder.
    var result:GeocoderResult = _address.geocoderResultSet.firstResult;

    // then we'll get the zoom level and center latlon to position the map on.
    _map.zoomLevel = 3;
    _map.centerLatLon = result.latlon;
    _map.mapType = MapTypes.HYBRID;

    var marker:SimpleMarker = new SimpleMarker();
    marker.address = new Address("Chicago");
    _map.markerManager.addMarker(marker);

    // Remove the black shape
    marker.removeChildAt(0);

    // Remove the remaining grey shape
    marker.removeChildAt(0);

    var yourCustomMarkerGraphics:Sprite= new Sprite();
    yourCustomMarkerGraphics.graphics.lineStyle(2,0000 00);
    yourCustomMarkerGraphics.graphics.beginFill(0xFF00 00);
    yourCustomMarkerGraphics.graphics.drawCircle(7, 7, 7);

    marker.addChild(yourCustomMarkerGraphics);

    }


    If all was well, Chicago would be replaced with Seattle. Thanks so much in advance…

  9. #9
    Member
    Join Date
    Sep 2007
    Posts
    75
    I didn't realize everyone was writing back on this thing. I have been extremely slammed.

    Let me first start off by stating that I am not an AS3 god by any means. I am merely someone that researched for months on how to accomplish a specific task within AS3 and asked a billion people for help and received 100 answers from people that do know what they are doing. If you have issues, there is a good chance that I probably cannot solve them. I worked extremely hard to find out the information that I did and wanted to save someone else the hassle that i went through so I put a step by step up.

    I finally abandoned the code because the downfalls of doing what I wanted to do outweighed the benefits.

    I had to remove the example I had on the website because Google was seeing as one of our keyword phrases and it wasn't bringing people anywhere. It is now a redirect.

    Wayne

  10. #10
    Member
    Join Date
    Sep 2007
    Posts
    75
    You can download the files here: http://www.scrfix.net/scrfix.zip

    Wayne

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  




Click Here to Expand Forum to Full Width

HTML5 Development Center