Integrate Google Analytics with Flash | Tutorial

The results are in and the requested topic is “Integrate Google Analytics into Flash.” The poll has been reset and is ready to recieve your post requests, so keep voting! It’s located in the side bar!

Overview:

Tracking your visitors and attempting to better understand them is a large part of even having content on the web. Since the days of visitor counters displayed proudly on every site, along with dozens of animated gifs to the days when site were designed solely with efficiency and conversion in mind. There are many services that will do this for a fee and other that will do it for free. A popular free web analytics tool is provided by Google. Google Analytics is started by including JavaScript on each page the user wishes to track. This JavaScript loads larger files from the Google webserver and then sets variables with the user’s account number. This JavaScript is used to track and log page views and visitors interaction with the site. This post discusses what to do if your site includes a lot of interactive flash elements you wish to track as well. With the little Google has published related to this(New Code, Old Code), I’ve tried to fill in.
Note: This explains how to set up to track flash events as page views, which does have a drawback- it inflates your pageviews in the analytics and in turn may skew your data. Il’l beposting again soon about how to use then new event tracking, which would track flash events not as pageviews, but as events and thus not inflate the page view count.

UPDATE

I now have an Event Tracking Tutorial as well with actionscript updates!
Event Tracking With Google Analytics & Flash/Actionscript Integration Tutorial

Steps:

  1. If you haven’t already, install Google Analytics on your site. (Note that your analytics tracking code must be placed on the page above the flash call(s) to _trackPageview or urchinTracker)
  2. Determine which events in flash you want to track.
  3. Place in the external.interface code in your actionscript at the specific event(s).
  4. Watch the events get logged in you Google Analytics Reports!

Example:

Here’s a simple example, say you want to track how many times an object is clicked or dragged by a user or how many times it bounces (something that could be tracked but doesn’t necessarily have any required user interaction). In this example flash file I have a ball which bounces off the walls and users can click to drag and even throw it, press the spacebar to create more balls and toggle the gravity on and off with the arrow keys (up is weightlessness, and down is gravity). Each of these events has code to communicate with Google Analytics JavaScript and track the events. I made my own function to call the google analytics code. Do I hear “but sometimes I want to use the new version of Google analytics, and sometimes I want to use the old one…” Have no fear, this function works for either one, or even both. If you’re not using the newer code the calls to the functions in the new code (pageTracker._trackPageview()) will be ignored and vice versa, if you are using the new code, then the calls to the functions in the old code (urchinTracker()) will be ignored, since the functions are not defined. You can track virtually anything with this method. I’ve exaggerated greatly in this example- just to show the variety of different ways this can be used. You might want to make certain the things you track will be useful and relevant for you.

Here is the swf file, I’ve added a text box that will print all actions that are logged to Google Analytics
[kml_flashembed publishmethod=”dynamic” fversion=”9.0.0″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2008/01/integrategoogleanalytics/integrategoogleanalytics.swf” width=”550″ height=”550″ targetclass=”flashmovie”]

Get Adobe Flash player

[/kml_flashembed]

track Google Analytics actionscript function
[cc lang=”actionscript” tab_size=”2″ lines=”40″]
function trackGA(action:String) {
//Old Google Analytics Code
ExternalInterface.call(“urchinTracker(‘/urchin/IntegrateGoogleAnalytics/”+action+”‘)”);
//New Google Analytics Code
ExternalInterface.call(“pageTracker._trackPageview(‘/pageTracker/IntegrateGoogleAnalytics/”+action+”‘)”);
trace(“Google Analytics Tracking: ” + action);
}
[/cc]

Calls to Google Analytics actionscript function
[cc lang=”actionscript” tab_size=”2″ lines=”40″]
trackGA(“swfLoaded”);
trackGA(“ball/”+_root.id+”/created/”);
trackGA(“ball/”+this.ballNum+”/released/”);
trackGA(“ball/”+this.ballNum+”/pressed/”);
trackGA(“ball/”+this.ballNum+”/bounced/top”);
trackGA(“ball/”+this.ballNum+”/bounced/left”);
trackGA(“ball/”+this.ballNum+”/bounced/right”);
trackGA(“ball/”+this.ballNum+”/bounced/bottom”);
trackGA(“gravity/on”);
trackGA(“gravity/off”);
[/cc]

Download:

IntegrateGoogleAnalytics.zip

Update:

Here is a screenshot of my Google Analytics Top Content after I search for “pageTracker/IntegrateGoogleAnalytics” (because I’m using the new code version, if I were using the old version I’d search for “urchin/IntegrateGoogleAnalytics”). This just shows that every event was logged to Google Analytics. This screenshot was taken mere hours after this post published.
Google Analytics Screenshot pageTracker/IntegrateGoogleAnalytics/

New Event Tracking technique tutorial rather than posting each event you want to track in flash as a pageview it can be a specific event!

53 thoughts on “Integrate Google Analytics with Flash | Tutorial

  1. I realize you have not done the event tracking blog post yet, but here is what I came up with last night to track rollovers in addition to an on (release)

    In my ga.js I added

    // Here is the new event object
    var rolloverEventTracker = pageTracker._createEventTracker(‘rollover’);

    My AS:

    box_mc.onRollOver = function():Void
    {
    ExternalInterface (“javascript:rolloverTracker._trackEvent(‘rollover’, ‘MyRollover’);”)

    box_mc.gotoAndPlay(2);
    };

    box_mc.onRollOut = function():Void
    {
    box_mc.gotoAndStop(1);
    };
    box_mc.onRelease = function():Void
    {
    getURL(“javascript:pageTracker._trackPageview(‘/flash/click/’);”);
    getURL(“http://www.yahoo.com”,”_blank”);
    };

    Normally the ga.js goes at the bottom of the page, immediately before the </body) tag. Do I need to put it above my Flash object code on the HTML page?

  2. Yes, I this is mostly correct, notice that the ExternalInterface.call() calls don’t need the ‘javascript:’ that is for getURL()
    Although, since I’m not a beta tester of the new Google Analytics Tracking Code, I can’t access the event tracking in my reports yet…

    And yes again, Here’s the answer straight from Google: “Google Analytics lets you track any browser based event, including Flash and JavaScript events by using the _trackPageview function, you can assign a page filename to any Flash action, and enter that filename into the appropriate goal or funnel step. Important: Please note that your analytics tracking code and calls to _gat._getTracker and _initData must be placed on the page above the call to _trackPageview.”

    So it seems that the new GATC should optimally be included at the top of the page rather than the bottom. I just include it in the header rather than the footer.

    I assume you need the event object placed before the flash, so the ga.js (exactly like you have it):
    var rolloverEventTracker = pageTracker._createEventTracker(’rollover’);

    and the AS:
    box_mc.onRollOver = function():Void {
    ExternalInterface.call(“rolloverEventTracker._trackEvent(‘rollover’, ‘MyRollover’)”);
    box_mc.gotoAndPlay(2);
    };

    Good luck! I’m anxious for this feature to be fully rolled out to all users!
    I will confirm as soon as I’m able to test it out!

  3. Ooh, that’s pretty nifty. We’ve been doing things like this for other commercial tracking systems like Hitbox, but I didn’t realise you could also do it with Google Analytics…

  4. Thank you very much for your site and what you’ve put into this page… but I’m out of my element and am hoping someone can post: 1) a simple HTML page with embedded SWF w/ Play button – such that I can see exactly where and how the Google Analytics code is used in the HTML in relation to the SWF and tag. 2) Its corresponding FLA and any files for download (similar to what you’ve done here for your example).

    Should it make any difference, I have a web page with a Flash file (when you hit “Play” button, it loads an FLV) I want to track IF and how long the Movie is viewed. I already have a listener on the Play button in Flash to “go to frame #” when movie ends. If Listeners apply to using GA and Flash — will these Listeners conflict?

    I have another site, which is one Flash File – but loads 4 different FLV movies via buttons I created, each Play button has a listener. Stepsdancecenteronline.com/videos.html

    Will I be able to use GA to track views & time viewed for this 4 movie Flash file? (that is, can this be done… not will I be able to set it up properly)

    Again, I learn best by example, and what is frustrating to me, is that many great tutorials leave just one or two things to “assumption” of the skill level of the audience. If I can see the code in context, my learning curve goes up.

    Thank you again, – even if you can’t accommodate this neediness on my part
    Kathy

  5. Excellent tutorial, and wonderful example provided. I’ve been looking for this info for a long time.

    Thanks a lot for putting in the time for this tutorial. I never considered tracking if the SWF loaded correctly, but it is a very good idea.

    I am looking forward to the Event Tracking blog entry.

  6. Excellent tutorial. I have been reading Advanced Web Metrics for the past few days. There is a small section on flash event tracking. It is somewhat informative. But your tutorial is better. Now I just have to piece together how to use if for a video.

    I am trying to track the clicks on Play, Pause, and time to download the entire video. This would be extremely helpful to track how people are viewing the video with different band widths as well as figuring out if they are viewing the entire video.

    Great tutorial…thanks.

  7. any question, how it could work in a Flash Air application like a widget, because I dont know if Air stuff embede Java and HTML with ja code?

  8. This would be absolutely great if I knew what you were talking about.

    The minute you started refering event tracking I was lost.

    You have an .swf which has buttons
    Those buttons click through for pages
    You want to track click throughs
    So you are placing the tracking code in the button layer movie’s actions layer?

    I feel like I need to go back about 4 steps.

  9. @Avangelist – This is a tutorial to track an event (something that happens in Flash) in Google Analytics as a pageview.

    This is a simple example about how to implement this idea. It can be pushed much further. This example shows how to track events with this ball (user interaction and not) in Google analytics. If we wanted to havea button going to another page it may be better to just put the analytics code on that page.

    You have a swf with buttons, which click through for pages? are these “pages” separate html pages or frames in your flash?
    You want to track the click of the button? That would be the exact way I track clicking this ball in the example. I’m placing the tracking code in the onPress event for that movieClip, as you can see in the source file provided.

    _root.ball.onPress = function () {
    startDrag(this);
    this.dragging = true;
    trackGA(“ball/”+this.ballNum+”/pressed/”);
    }

    thanks for reading

  10. Hi,

    I tried this code, but in my Google Analytics page I don’t see any separate entries for the events that I created. Do I need to create some corresponding entries in GA settings manually too?

    Thanks,
    Mukesh

  11. Mukesh – Nope, it should show up, be sure to give about 24 hours for the hits to show up in your reports. But in this example I make calls to trackGA(”ball/”+this.ballNum+”/pressed/”);, so you can search in the top content page of your reports for a page containing (in this example) “ball/” or “/pressed/” and if everything happened correctly they should show up there.

    If you aren’t as patient as that though, you can see live evidence of the tracking being sent to google analytics… Get the firebug extension for firefox and you can easily monitor network calls. This will show you the header and parameters sent with all calls to google analytics, you can see the path that gets sent! Pretty cool, eh? It will look like this “GET __utm.gif?utmwv=……sending tons of parameteres!

  12. Thanks Evan. Actually I had waited for 48 hours before contacting you. What you suggested about Firebug sounds cool. That will help me in finding if I am making any syntactical or other mistake.

    Thanks,
    Mukesh

  13. Hi.
    Thanks for all the info.
    My website is all flash (swishmax to be precised).
    I have a menu with several buttons. Once a button is released the movie goes to a frame and plays it. How do I add google analytics to track that somebody clicked that button?
    Here is the simple code – but unfortunately no answer:

    on (release) {
    _root.gotoAndPlay(66);
    }

    Please make it real simple! Thank you

  14. @Looney – try this:

    on (release) {
    traceGA(“buttonRelease/66”);
    _root.gotoAndPlay(66);
    }

    function trackGA(action:String) {
    //Old Google Analytics Code
    ExternalInterface.call(“urchinTracker(‘/”+action+”‘)”);
    //New Google Analytics Code
    ExternalInterface.call(“pageTracker._trackPageview(‘/”+action+”‘)”);
    trace(“Google Analytics Tracking: ” + action);
    }

    You can send a different action on each button, and analytics will tell you reports for each button pressed. Or you could put the analytics call onto the timeline, so when they go to a certain frame the function is called to log the tracking.

  15. There seems to be a problem with the line:
    traceGA(“buttonRelease/66”); It appears yellow meaning there is an error.

    Here is what I have once I added the code you gave to me:
    on (release) {
    traceGA(”buttonRelease/66″);
    _root.gotoAndPlay(66);
    }

    function trackGA(action:String) {
    ExternalInterface.call(”pageTracker._trackPageview(’/”+action+”‘)”);
    trace(”Google Analytics Tracking: ” + action);
    }

    Now the button is inactive. Any idea?

  16. Im using AS2 and with getURL method..
    getURL(“javascript:pageTracker._trackPageview(‘/filetrack/1.html’);”);
    – it does work but when i try to get the page number dynamically..
    getURL(“javascript:pageTracker._trackPageview(‘/filetrack/’+_root.pageNumber+’.html’);”); IT DOES NOT WORK.. someone please help where im doing wrong- i can however trace the root.pageNumber and it shows the page number right but for some reason.. it does not work- please help.

  17. i used your example and it’s not working for some reason… although i don’t understand why you’re passing the javascript function’s parameters all within the contents of the ExternalInterface.call’s first parameter, instead of:

    ExternalInterface.call(“pageTracker._trackPageview”, action);

  18. Abhishek, you forgot to add 2 double quotes, this should work:

    getURL(“javascript:pageTracker._trackPageview(‘/filetrack/'”+_root.pageNumber+”‘.html’);”);

  19. By placing the Google tracking script in the html file that calls up the .swf file, will that work properly? Right now Google will read the HTML page, but none of the flash functions. I used some of your code and everything worked ok in Flash.
    thanks

  20. In google analytics can u show me way how to embed google analytics in a media player(for example: JW player)

  21. I’m using a single Flash button to play multiple audio files,. So I just update the HTML to reflect the audio file I want played. However I want to track each audio file seperately. Can I track the clicks on the play button, in Analytics, without updating the Flash file?

    Web page: http://www.lyonspr.com/listen.php

    Is there Javascript I can use instead? Any ideas?

  22. this is for an Advent calendar .. I need to drop some analytics into a Flash movie .. using a flash file as an index which has 24 buttons .. could I put the analytics on the index to show which buttons are being clicked .. or each of the 24 flash movies it launches.

    I’m not quite sure how the 24 flash files are being accessed (as it’s behind a corporate firewall, so I cannot see it) an I’m not so much of a flash expert (you guessed that didn’t you!) .. can the analytics code be put directly into the flash move somehow without any need to drop anything into an HTML page?

  23. @ Greg Johnson – I’d think you have to update the flash file and include the script to communicate with analytics. You could use an html button pretty easily and do all the control with javascript as well, not sure what functionality you have wrapped up in flash though. Good Luck!

    @DavidF – to do the flash google analytics communication you shouldn’t need to access the html as long as it has google analytics properly installed. (Keep in mind that if it’s not your google analytics tracking code account number you wont have access to the analytics though). If I understand correctly, I’d say put the tracking code in your flash index file and each time you click one of the 24 buttons, send a call to google analytics.

  24. So my question is…if I wanted to track… for example, if I run this banner (http://mercl.com/glucocil/banners/gluc_160x600.html) on http://www.WebMD.com.

    I’m not the guy putting the code on WebMD.com so is there a way to get the code all together so what I send him can be placed easily?

    Not sure if I’m making sense. I know on my own page I could put the code wherever I want, but counting on someone else…when you’re paying alot…another issue.

  25. I am trying to track when someone watches a flash movie on my site I have used the following code on the play button but I don’t see any results in GA it has been over 24 hours since I have added the code and put it on the site. the rest of GA is updated but it does not show the video anywhere.

    on (release) {
    //Track with action
    getURL(“javascript:pageTracker._trackPageview(‘/video/getDeal.php’);”);
    _root.gotoAndPlay(4);
    myVar = “Video Play From GetDeal”;
    }

  26. I’ve done everything in your example ….. nothing is getting recorded to GA. Only the page hits seem to get recorded.

    Can you be more specific with this part

    ” (Note that your analytics tracking code must be placed on the page above the flash call(s) to _trackPageview or urchinTracker)”

    My GA code that is in my HTML file is sitting right above my closing BODY tag.

    I have tried putting the code right above my Flash embed statement too … still doesnt work.

  27. Hey buddys,
    the new google code looks like this:

    var _gaq = _gaq || [];
    _gaq.push([‘_setAccount’, ‘UA-XXXXXX-X’]);
    _gaq.push([‘_trackPageview’]);

    (function() {
    var ga = document.createElement(‘script’); ga.type = ‘text/javascript’; ga.async = true;
    ga.src = (‘https:’ == document.location.protocol ? ‘https://ssl’ : ‘http://www’) + ‘.google-analytics.com/ga.js’;
    var s = document.getElementsByTagName(‘script’)[0]; s.parentNode.insertBefore(ga, s);
    })();

    How did I have to change the AS-Code in my project??

    //Google Analytics Calls
    function trackGA(action:String) {
    //Old Google Analytics Code
    ExternalInterface.call(“urchinTracker(‘/urchin/IntegrateGoogleAnalytics/”+action+”‘)”);
    //New Google Analytics Code

    ExternalInterface.call(“pageTracker._trackPageview(‘/pageTracker/IntegrateGoogleAnalytics/”+action+”‘)”);
    trace(“Google Analytics Tracking: ” + action);

    }

    ///Listener

    bild.addEventListener(MouseEvent.CLICK, abspielen);

    function abspielen(evt:MouseEvent) {
    trackGA(“Bild_Header_Klick”);
    }

  28. Hi
    With the new Google Tag:
    var _gaq = _gaq || [];
    _gaq.push([‘_setAccount’, ‘UA-XXXXXX-X’]);
    _gaq.push([‘_trackPageview’]);

    I change my As code by:

    onPress = function() { ExternalInterface.call(“_gaq.push([‘_trackPageview’, ‘/form/form_passed’])”);
    ExternalInterface.call(“_gaq.push([‘_trackEvent’, ‘Form’, ‘Send’, ‘Contact Form’])”);
    }

    For me it looks working fine!

  29. Thanks a lot for this tute! Made Google tracking for AS2 very clear. I have just one question though.

    When I check ‘Activity’ in safari, I only get the loading of the Google test gif and a call to the ga.js file once, no matter how many times I click. Is this the usual result?

    I would have expected a url call with loads of vars appended.

    Thanks for the tute once again.

    1. Thanks Joe – I’m not sure about watching activity in safari, I always develop in firefox. It’s a free download and I’d highly recommend it as well as the firebug add-on. I wouldn’t know where to start looking for that in Safari, thinking about their track record, I’d guess Apple doesn’t allow it.

  30. Hi Evan,

    Thanks for the response. I do use firebug and Safari has a built-in developer section which is pretty cool, although prone to crashing 😉

    I was using Firefox but wasn’t getting the gif file which also contains the tracking variable values. It turned out that I was using the dated .js function call in my html page DUH!

    I’m now getting the gifs to fire with every click 😀

    Now I just need to work out how to call two google analytic accounts (Ours and the clients)!

    Thanks again for the tutorial, I couldn’t have learnt this without it 😀

    Joe

  31. @Gtex
    How did you change your action script, which fields did you change I’m looking for a way of using the ExternalInterface.call(“_gaq.push([‘_trackPageview’, ])”); way, please can someone instruct me on the changes to the Logging.as that will need to be made to achive this.

    Thanks – Caius Eugene

  32. Really very useful tutorial. Thanks a lot. Is there anything need to do apart from this?

    That means , for learning i used to upload your sample files and activated the GA code in the HTML. But still it was not generated the report as the screenshot you given. Is there anything need to do except you provided information? Need to set any analytics setting in account?

    Please assist.

    Thanks in advance

    1. @Azar – I do know that google analytics has pushed some updates in the past couple years. I’ve been using a library recently to do my analytics tracking:

      http://code.google.com/p/gaforflash/

      check it out, eventually I’ll put an updated ‘google analytics for flash’ tutorial up explaining how to use this library.

  33. Hi

    very useful article.
    I have a website and want to track which pages visitors are going. For example , i have a gallery Seven Seas Yachts – Legend 54 ,
    and i want to track this image in GA. What i must change to as file and what to html for tracking this link. My web site use AS2 and i use already with Google analytics code, in you example use logging.as file, should use it too?

  34. Hi, I’m trying to incorporate this into a project and I’m not seeing any info from Google that it’s working.

    I have a main SWF loading external swf files. Within the main swf on the buttons I have…

    on(release){
    trackGA(“loaded/Gerry”);
    this.loadMovie(“Main/gerry.swf”);
    }

    I’m also loading

    import flash.external.*;
    #include “logging.as”

    within the first frame and the logging.as is present.

    What am I doing wrong?

    Thanks.

  35. What if you had a flash app that accesses Analytics data rather than inputs data for a leader board widget? Is it even possible?

    I’ve been searching for hours and have only found an app that uses prompted XML feeds but nothing real time

  36. Me he registrado a GA y la he activado, puse su swf en un index.html junto con su codigo JS, pero aún así no registra los movimientos de tu swf, supongo que hay algo más detrás de todo esto. :/

Comments are closed.