Quick Tip: How to use Google Analytics for Tracking in Flash

Quick Tip: How to use Google Analytics for Tracking in Flash

Tutorial Details
  • Difficulty: Intermediate
  • Program: Flash

In this Quick Tip I’ll show you how to examine the way visitors are using your websites, widgets and games. Then we’ll look at how to improve them based on this info!


Introduction

Building nice looking websites is great; building websites that have a high Return Of Investment is priceless.

Recently I joined the web team of a Brussels based communication agency, a team with expert knowledge in the fields of user experience design, content strategies, software development, and interaction design. We spend a lot of time on wireframes, storyboards, and prototypes, which guarantees that the functionality and the content of the websites are optimal before any graphical design takes place. This means our websites have a solid base to be built upon, which results in a higher ROI with less time spent on development.

A huge part of our work is under the hood: Google Analytics inside Flash.

This tool allows us to measure how well our sites are doing against our predefined goals: bounce rate, click paths and even custom measurements like how many people scrolled a certain page. Our specialists analyze all this information and use it to optimize the website. If you’re not measuring how people are using your site, you can only guess about its successes and failures.

The following setup is a stripped-down version of an image gallery; Google Analytics allowed the client to discover which images triggered the most interest. I’ve left out the actual gallery building as it is beyond the scope of this tutorial; there are plenty on Activetuts+ already though – just search for “gallery”.

We will focus on how to set up Google Analytics to put a smile on your clients’ faces (and probably yours too…)


Google Analytics in Action

Here’s the simplified image gallery:

As you can see, when an image is clicked, its identity gets sent over to my Google Analytics account. Later on, I can look at all the statistics of which images were clicked, at which times, in which countries, and so on.

(Of course, you’ll remove all that overlaid information when it’s live on your own site!)


Step 1: Understand the Benefits

Imagine yourself working hours, weeks, even months on a website. You successfully deliver the files before the deadline, but a few months later it’s clear that – despite being beautiful – the site is not attracting as many customers as your client expected. Google Analytics helps you to review visitors’ browsing habits and discover which parts of the site could be better highlighted. Beauty is great, but I believe that Return Of Investment should be your main priority.

In another scenario this same tool helps you to understand what area of your website has the most page views, how many times visitors wanted to contact you, or which elements of your portfolio visitors love the most. How many benefits can you think of for your site?


Step 2: Set Up a Google Analytics Account

If you don’t have a Google account already, sign up for one here – it only takes a few seconds.

Once that’s done, head to http://google.com/analytics and sign up for an Analytics account. There you can give an account name for the websites you want to track.

google-analytics-for-flash

Step 3: Inside the Machine

Head to https://google.com/accounts/ManageAccount
and use your mouse skills to click Analytics.

Great, we are now in the Overview page. You should see your Analytics account name; click it and you’ll find yourself at the website profiles.

google-analytics-for-flash

If you haven’t set up a website to track, simply click ‘Add Website Profile’. Enter your domain name and Country, then click Finish.

google-analytics-for-flash
google-analytics-for-flash
google-analytics-for-flash

Step 4: Retrieve your UA Code and Tracking Status

The Tracking Status page will automatically appear:

google-analytics-for-flash

The most important part is your web property ID. This is a unique number Google Analytics will use to send and store your website’s traffic. (Copy this UA code for use later in Flash, or write it down.) For this introduction we’ll simply keep all the options at their defaults.

If you’re going to embed your SWF on your own webpage, the javascript code must be pasted right before the </body> tag in the page’s HTML. This will allow you to keep statistics for the actual page itself, as well as for within the SWF. It’s worth inserting this code in every page on your site.

All this is great, but you still won’t be able to pinpoint your visitors’ interaction in great detail, as the HTML is blind to your actual SWF / Flash content.


Step 5: Gathering Wood

To make sure you can see which parts of your SWF are being used, head to http://code.google.com/p/gaforflash/.

This amazing open source AS3 API has a lot of great features for integrating GA into Flash, but even with our biggest and most complex websites, we’ve only ever used two functions. (More about these later on.) Make sure you download the latest installment on the right of the page. (Come back any time to read the wiki, issues etc, to learn more about this vast API.)

google-analytics-for-flash

Step 6: Install the Components

The zip contains a documentation folder with the entire API layout to help you along the way; a library folder (lib) where you’ll find the two components; and some text files you probably won’t ever read. At least I didn’t ;]

To install the components, make sure Flash is closed, then navigate to:

  • Windows users: C:\Program Files\Adobe\Adobe Flash CS X\language\Configuration\Components
  • Mac users: Macintosh HD/Applications/Adobe Flash CS X/Configuration/Components

At this point you need to create a directory named ‘Google’ and copy the files from the \lib\ folder in the zip to it.

Basically the two components give you the same functionality but are developed for two different purposes. The Analytics component is for those who are unfamiliar with AS3. I assume most of you are already using AS3, so we’ll use the AnalyticsLibrary component.


Step 7: Feeding the Fire

Inside Flash, open the FLA for the project you’re working on, click Window > Components, and drag the AnalyticsLibrary component to your library.

google-analytics-for-flash

Step 8: Action! (Script)

Whether you’re coding on the timeline or using a document class, you’ll need to do some imports:

//import the Analytics classes
import com.google.analytics.AnalyticsTracker;
import com.google.analytics.GATracker;

Also, in your code, create a new instance of the AnalyticsTracker:

var tracker:AnalyticsTracker = new GATracker( this, "UA-XXXXXX", "AS3", true );

The parameters are: stage, UA code, actionscript 3 mode, visual debugger on/off. Leave them all as I’ve set them, apart from the UA code which you’ll need to swap for your own. Set the last parameter to false when you are done with your testing phases, as when true it will create an overlay on top of your SWF file like in the example above.

Test this out by adding a Click event listener and handler to one of your movie clips or buttons:

myMc.addEventListener (MouseEvent.CLICK,onClick);
function onClick (event:MouseEvent):void
{
	//make your clients happy.
    //use 'event.target.name' instead of 'event.target'
	//this will display 'myMc' instead of [object myMc], which is obviously a nicer output.
	var mySelection:String = event.target.name;
	tracker.trackPageview ("gallery = " + mySelection);
}

Here we’re using the trackPageView() function. Use this for navigation purposes. You can add a string so your client knows what part is being tracked. In this case we’re tracking which gallery has been triggered. So copy and paste this code everywhere you want to track your interactions and give an understandable String to the data.

For example, if you have a “call to action” button on stage to lure potential new clients, you could write:

tracker.trackPageview("Hire me");

…in the Click event handler for that button. Or if you want to track how many times they have read your disclaimer:

tracker.trackPageview("Disclaimer");

I’m sure you get the idea.


Step 9: Event Tracking

Use event tracking if you want to track what video or MP3 event is being played, or when the user pauses it – things like that. It’s basically for any action that doesn’t represent opening a “page”.

The code looks like this:

trackEvent(category, action, label);

For example:

tracker.trackEvent("profile videos", "play", "first video: introduction");

Additionally you can add a fourth parameter. This can represent any value you like, but it must be an integer (whole number). For example, you might want to pinpoint the exact time when the video was paused.

This is great to see how well your streaming or downloading performs for your visitors (not everyone has top class Internet connections):

var currentTime:Date = new Date().time;	//get the current time
//load the video here
var readyToRoll:Date = new Date().time - currentTime;	//get time taken to load the video
tracker.trackEvent("profile videos", "playing the video", "video 1/3: introduction", readyToRoll);

Step 10: See the Data in Google Analytics

Go to http://google.com/analytics/settings/ and click your account name. Next to your domain name, click View Report.

google-analytics-for-flash

Here you will see a timeline. (Please note: depending on your server response time it can take a while before the data gets stored, but it shouldn’t take too long.) Select the dates for when you have been testing using the calendar in the top-right:

google-analytics-for-flash

Locate the Content Overview; here you can see which events or buttons were triggered:

google-analytics-for-flash

As you can see, as I explained a few steps back, event.target.name displays a “nice” name like “/gallery = gallery 1″, while event.target returns something like “[object picture1]“

Clicking on one of these links – for example, “/gallery = gallery2″ – you will be able to see in-depth information, like what screen resolution your users have, when you choose an option in the drop-down menu.

google-analytics-for-flash

There’s a deep and rich information source in nearly every single branch of the Google Analytics module. It’s nearly impossible to list all of them. Don’t be afraid; look around and see what data you can provide to your clients and yourself.


Step 11: Eliminate Yourself from the Stats using Filters

It’s a good idea to filter out your own behaviour; otherwise, it will give you incorrect data since you will probably test this in great detail.

You can do this by filtering all activity coming from your IP address – though please note, this will only work if you have a static IP address. There is a lot of documentation in the help files; I can’t cover it all here. Check out http://www.google.com/support/googleanalytics/bin/answer.py?hl=en&answer=55481

Filters can also be useful for other reasons. Here is some more information: http://www.google.com/support/googleanalytics/bin/topic.py?hl=en&topic=11091


Step 12: The End is the Beginning…

In this Quick Tip I’ve only covered a snowflake on the tip of the iceberg of what you can do with this amazing API. It’s a quick overview on the two most beneficial functions that we deal with to improve our websites and match our clients’ wishes.

You can also set predefined goals, group users that (for example) use widescreen monitors, base your Analytics on search engine keywords and so on. For your clients, you can send an email with daily, weekly or monthly reports (as xml, PDF, or other formats), or even give them access to your Analytics page. If you’d like more information, please ask in the comments!


My Opinions on Search Engine Friendly Flash Websites

Although it is beneficial to read and trace your visitors’ interactions, this is a long way from using Flash in an SEO-friendly world. I’ve warmed you up for optimal website design and focusing on Return of Investment, but we’re not there yet.

A good next step would be to look into the Gaia framework, and use its mighty setup to work with swfaddress and deeplinking. This will allow you to track individual pages of your website project and in combination with your newly learned Google Analytics magic, I am sure not only your clients will smile.

Editor’s Note: We have some Gaia tutorials lined up, don’t worry ;)

I’ve been working for over 10 years in the graphic design world, and never had so much power to know exactly what my clients and visitors want. I often like to call it “free marketing and research from your desktop”. (If you are wondering why my own site isn’t using this technology, well honestly… I hope to re-launch by mid 2010 *sips coffee*)

I hope this opens new doors for you and boosts your skill set. Good luck and have fun!

Tags: Tips
  • André

    Great and very usefull tutorial!!

    Thanks !!!

  • Pingback: Quick Tip: How to use Google Analytics for Tracking in Flash … | Search Engine Optimization

  • http://ilopezdeaudikana.com mutiu

    Thank you…. I have “played” before with google analytics but never heard of gaforflash, so this will be very helpfull in my next projects….

  • http://www.ispeakdesign.co.nz/ Rainui

    Exactly what the doctor ordered! And very easy to follow! Thank you so much!

  • http://labs.dariux.com Dario Gutierrez

    Excellent component and tutorial dude!

  • Pingback: Quick Tip: How to use Google Analytics for Tracking in Flash … | Drakz Free Online Service

  • http://www.cbesslabs.com Sebastian Bratu

    Great tutorial, I would love to work in an agency that goes this detailed about the setup. This is what separates a “hobbyist” creative agency and a professional studio. They know how to make a workflow.

    Thank you for the tutorial, I will definitely track my own flash websites, when they’re done!

    • http://www.nitras.be peter
      Author

      Thanks for the kind words, The best advice I can give is to put yourself in the viewpoint of your user.
      Step aside of what “you like” or “you experience”, act dumb, act unaware of what you as a business are doing.

      But admittedly, its merely when I joined the webteam of this company I got to see a bigger picture.
      It’s good and hard at the same time to reflect this at my own site/older work, and see what new paths I had to learn. (still not there, but that’s our job, graphic / web is ever expanding, there’s no stop)

      Good luck!

  • John Bon

    Looking forward to the Gaia framework. I’m going to be building my first site w the gaia framework in a bout two weeks. Would love some good tips.

  • http://www.burnandbass.com Ice

    Well, SWFAddress have built-in Google Analytics support. It is very simple to use it – just small, generated by GA JS have to be added to the page.

  • http://www.flashmoto.com/ Flash Moto CMS

    Thanks for the informative tutorial. We use the similar system in our Flash cms providing an opportunity to integrate Goggle analytics in order to track each page of the flash website.

  • http://www.nopun.com Noel Wiggins

    Wow this is tremendous, I have to admit this is one of many reasons why I didn’t like the thought of designing an all flash website.

    But this is great news I can’t wait to test it out.

    Thanks and Regards

    Noel for Nopun.com
    a graphic design studio

  • http://mattson.net Robert

    Did you want to tell them about the negatives of having google work for you? OR shall I?

  • http://www.nitras.be peter
    Author

    Thanks for all great comments.
    I am working on more user / interaction based tutorials / quicktips. Also a few design based strategy tutorials might show up soon.

    Glad you all like it.
    Peter

  • http://www.himoaito.com Tiksa

    Great tut!

    I’ve been waiting for this, keep up the good work!

  • http://felixchi.com Felix

    Does this work in AS2?

    • Avinash

      No this does not in AS2, this start working with AS3

  • Pingback: Forex Trading Books – Forex Trading By The Books | Forex Trading Cash

  • http://blog.activetofocus.com activetofocus

    great!!

  • http://ginz.weebly.com Pedro Lopes

    The most usefull tutorial I ever found!

  • Pingback: Spot Forex Trading – Spot Forex Trading and Forex Futures Trading | Forex Trading Cash

  • http://www.dcomsoft.com/obfuscate-swf.html Roy

    Excellent!

  • http://www.dcomsoft.com/obfuscate-swf.html Roy

    Excellent one!

  • Pingback: Just an ordinary blog

  • Pingback: Charm Necklaces Add Personality | eastwestbakery.com

  • Nick Snyder

    Any idea what this means guys? The Google is not helping right now…

    “Loader.load()” could not instanciate Gif Request

  • Zankhana

    Great article. Was looking for exactly the same thing. Thanks a ton.

  • http://varthabharathi.net Muhammed Ali

    How do i give link to open an URL with Google analytic action script when clicked on the button.

    • http://www.nitras.be Nit’ras
      Author

      You can add an URLRequest in the onClick event like f.e so:

      function onClick (event:MouseEvent):void
      {
      //make your clients happy.
      //use ‘event.target.name’ instead of ‘event.target’
      //this will display ‘myMc’ instead of [object myMc], which is obviously a nicer output.
      var mySelection:String = event.target.name;
      tracker.trackPageview (“gallery = ” + mySelection);

      var link:URLRequest = new URLRequest(“http://www.active.tutplus.com”);
      navigateToUrl(link,”_blank”);
      }

      That should float your boat ;)

  • Pingback: Just an ordinary blog

  • Pingback: Our favorite tweets of week 9 | PIXEL SHOP

  • http://www.cwm.co.il Tamir Cohen

    You Are Great!

  • Jan

    THANK YOU! Your tut was so easy to follow and I finally got my GA code working in the time it took to read over the content.

  • Jan

    How would I add this to a combo box? I would like to know which drop down was selected. I got it working on my other file with a basic event handler. I”m a little stuck on this one. thanks.

    //import the Analytics classes  
    import com.google.analytics.AnalyticsTracker;  
    import com.google.analytics.GATracker;  
    var tracker:AnalyticsTracker = new GATracker( this, "UA-00000000-0", "AS3", true );  
    stop();
    combo.addItem ({label:"Male 35",data:"male35"});
    combo.addItem ({label:"Male 45",data:"male45"});
    combo.addItem ({label:"Male 55",data:"male55"});
    combo.addEventListener (Event.CHANGE, changeHandler);
    
    function changeHandler (event:Event):void
    {
    gotoAndPlay (event.currentTarget.selectedItem.data);
    var mySelection:String = event.target.name;  
    tracker.trackPageview ("data = " + mySelection); 
    } 
    • http://www.nitras.be nit’ras
      Author

      Hi Jan,

      currently based on your code, the mySelection refers to the name of object what the event triggers. in other words combo.

      Change mySelection to:

      var mySelection:String = event.currentTarget.selectedItem.data (or) event.currentTarget.selectedItem.label
      tracker.trackPageview (“data = ” + mySelection);

      on a sidenote: its better to use currentTarget instead of target for components, as target stays the same during the event while currentTarget takes notice of any possible changes during the event handling (targetting, phasing, bubbling, etc).

      happy analytics!

  • http://www.e11world.com e11world

    Is there any alternatives to this for AS2?
    I did some research and haven’t really found anything yet.

    • http://www.nitras.be nit’ras
      Author

      Alas not :/ and then again (partly)yes. swfObject & swfAddress can give you similar results but still not in great detail such as pinpointing which button/movieclip/function/whatever has been triggered.

  • Pingback: ATP Tuto » Création Newsletter

  • Ramona

    My operting system is Windows 7. After installing CS5 Web Premium, the path is:
    C:\Program Files (x86)\Adobe\Adobe Flash CS5\en_US\Configuration

    However, there is no Components folder currently. Do I create one there?

  • Racheld

    I’d like to use a URLRequest in an onClick event as discussed above, but I keep getting the following error in my code. Can someone help?

    TypeError: Error #1009: Cannot access a property or method of a null object reference.
    at myVideoPlayer::MyVideoPlayer_CDN/linkToSrsPg()

    Here’s my code:

    myLogoLink.addEventListener(MouseEvent.CLICK, linkToSrsPg);
    myLogoLink.buttonMode = true;

    function linkToSrsPg(e:MouseEvent):void{

    var mySelection:String = e.target.name;
    tracker.trackPageview (mySelection);

    navigateToURL(new URLRequest(“http://www.kidscanpress.com/Canada/CitizenKid-C5065.aspx?section=5&series=2″));

    }

    Any help would be oh so appreciated!

  • Jan

    Thanks So much nit’ras.

  • Pingback: Installing Google Analytics into your Flash CS4 SWF | Anywhichway Development Labs

  • Lisa

    Thanks – this simple step-by-step guide is very much appreciated!

  • http://islamforhumanity.wordpress.com sajeer mohammed

    amazing and excellent round up!

  • http://www.gfjfgfg.com Felicita Rasmus

    Wow! Thank you! I continually wanted to write on my blog something like that. Can I implement a portion of your post to my site?

    • http://www.nitras.be Peter
      Author

      Sure, if you reference to this post and my website (http://www.nitras.be) we’re friends :)
      thanks !

  • http://www.quali-x.de wiyono

    i have problem with this:
    C:\Program Files\Adobe\Adobe Flash CS X\language\Configuration\Components

    “Languange” not stay there, but stay “C:\Program Files\Adobe\Adobe Flash CS X\DE\Configuration\

    “Component is not there too?

    Can you help me?
    Thank you

  • http://www.think360studio.com/ Nicki

    Great and very useful tutorial!!

    thank you so much :)

  • Pingback: How to use Google Analytics for Tracking in Flash | Webpappa

  • Mark

    Is there a way to have it automatically send an event when the flash is opened. For example, a video autoplays when the file is opened. Instead of having the user CLICK on the play button to send the information to google analytics, it would do so when the page with that content loads?

    • Mark

      one of the things I am attempting to do is put an SWF file within a PDF file and have it autoplay when the PDF is opened, therefore, sending information that the PDF was clicked as a pageview to google analytics.

      • http://www.nitras.be Nit’ras
        Author

        Sure, Simply put in the tracker code in the function that plays the video.
        for example:

        //import the Analytics classes
        import com.google.analytics.AnalyticsTracker;
        import com.google.analytics.GATracker;
        var tracker:AnalyticsTracker = new GATracker( this, “UA-00000000-0″, “AS3″, true );
        var myDate:Date = new Date();

        function autoPlayVideo(e:Event):void
        {
        tracker.trackPageview (“PDF opened on ” + myDate + ” with video ” + e.currentTarget.name);

        }

        Don’t mention the myDate, its just a little neatness to see at what date, hour, etc a user has opened your pdf. Since you’re tracking activity, you also might pinpoint it :) Where e.currentTarget.name is the name of your video variable.

        Basically you can put the tracker where ever you want and trace out whatever you want in there.
        You don’t need to reference events, That said you could even simply track tracker.trackPageview(“Hi I just got tracked”)

        If you want event specific tracking please refer to step 9:
        tracker.trackEvent(“profile videos”, “play”, “first video: introduction”);

        Hope this helps.
        Sorry for the late answer… I wish this board/comment section had notifications.
        regards, Peter

  • http://www.successfulsite.com Portland SEO

    Thanks for tips.They are really informative and knowledgeable.

  • Iain

    Hi there, great tut, but how do i remove the “overlaid information” I can’t seem to work out that bit?

    • http://www.nitras.be nitras
      Author

      That is covered in the tracker code itself.
      As I mentioned the last property “true” displays this overlay, set it to false once you publish after development.

      aka
      var tracker:AnalyticsTracker = new GATracker( this, “UA-00000000-0″, “AS3″, false );

  • http://www.ramidinc.com Carlos

    My whole website is a couple of SWF files that load into a main SWF file, but I am not using any HTML files can I still make this work without the html’s.

    • http://www.nitras.be nitras
      Author

      Absolutely, you only need the tracker code in AS3 which sends a request to the googleAnalytics tracker.
      Reason why i am sure about this is, cuz when you test / publish your movie, it also sends this request perfectly!

      enjoy :)

  • http://www.lloydp.co.uk Lloyd

    Fantastic write up, thank you for your time.

    The only minor comment I would have would be that trackPageView needs to be trackPageview.

    Silly I know, but the error message thrown could cause some confusion.

    • http://www.lloydp.co.uk Lloyd

      I’m also getting the following error message when running from the published HTML file:

      “Loader.load()” could not instanciate Gif Request.

  • http://www.pilpeliot.com Sarit

    This was helpful.. Thanks!

  • Phinrich

    Hi and thanks for a GREAT tutorial on this aspect of Flash.

    I have set up a test app as instructed and it seems to work fine and I have also set up a Google Analytics account which also seems ok except that being a first-time GA user I am a little unclear on how to set up Goals and so link the app to my Google Analytics account (other than the code in the app). Apart from the code in your tutorial app and defining the name of the test app in GA do I need to set anything else on GA in order to see Reported activity ? For now the Report is blank? Perhaps theres a good tutorial on setting up GA to be awake to your app. Or do I have it all WRONG ?

    Thanks

    Paul