Flash CS3: Google Analytics & Flash content

Header

Last week I’ve been asked a few times how to use the google analytics code with a flash project, the solution is actually pretty simple but very effective, while google provides you with some “help content” it proves itself that the help page they have is quite hmm.. useless.. You don’t want to show the viewer of your application that you are sending data to google by opening a new webpage.. yuk..

  1. First it’s not how you should do it
  2. Second there are better solutions to achieve the same result without having pop-up’s appearing all over the place.

If you already know how to set up a Google Analytics profile jump to STEP5 .

1. Let’s start off by browsing to http://www.google.com/analytics and log-in with your Gmail account or sign up for a new account.
Login

2. Then add a website profile by clicking on the “Add Website Profile” on the bottom right corner
addWebsite

3. Give the needed information: your website’s URL and timezone location for proper date & time display
ProfileCreation

4. On the next screen you’ll see a page with a Javascript in the textbox and 2 tabs, one tab is for the old google analytics code and the other is for the new google analytics code which has been improved heavily, we are going to use the new code, as it doesn’t make anymore sense to use the old one, copy the javascript code and paste it on your notepad for later usage.
googleCode

In this example I’m going to show you how to track the user clicks from a simple video chooser application.
As I’m not going to explain how to create the video application, I give you here the possibility to download the .fla I’ve created

Download the sample .fla

5. Let’s open our gaTracking.fla document, there you’ll find 2 buttons and a black frame, all graphical objects are on a layer while the actions are on the top layer. Select the actions frame and press the F9 key to open the actionscript panel. You’ll find the actionscript for the video handling and button actions, if you test this fla you’ll see that everything is working as it should, you press Clip1 and the associated video is played.
Flash Video

6. Now let’s get back to what we are trying to achieve, first of all let’s publish the current .fla document so we have a .html site that we can work with, therefore select File -> Publish, open the newly created HTML page with notepad, wordpad, dreamweaver or whatever fits your needs, and paste the give Google Analytics Javascript code in the html page before the tag.

Here a sample Google Analytics code in my HTML which you can also find on the downloadable sample file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>index</title>
<script language="javascript">AC_FL_RunContent = 0;</script>
<script src="AC_RunActiveContent.js" language="javascript"></script>
</head>
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
var pageTracker = _gat._getTracker("UA-XXXXXX-X");
pageTracker._initData();
pageTracker._trackPageview();
</script></html>

UA-XXXXXX-X needs to be replaced with the code that google assigned to your account.

7. Now let’s add the tracking options to our buttons. Go back to Flash, select the first frame containing the actions and create a new function right after the initClip() function:

1
2
3
4
function trackGA(trackingString:String):void{
	var targetURL:URLRequest = new URLRequest("javascript:pageTracker._trackPageview('/root/"+trackingString+"');");
	sendToURL(targetURL);
}

the function expects one argument called trackingString the string can be whatever you want, just be aware that the string you passing will be the one that is going to show up at googleAnalytics report.
Google Analytics Result

Everything inside the parentheses “()” can be user defined, in my case I’m using the root/ before the string so that I know that the flv is located at the root of the webserver.

Then we create a new URLRequest object holding the url to the javascript which has been embedded into the html page before, and with the last function sendToURL(targetURL) the js is called and google does the rest.

Last but not least below the complete code used for this example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
var nc:NetConnection = new NetConnection();
nc.connect(null);
 
var ns:NetStream = new NetStream(nc);
ns.client = new Object();
 
var myVideo:Video = new Video();
 
var clip1:String = "clip1.flv";
var clip2:String = "clip2.flv";
 
clip1Btn.addEventListener(MouseEvent.CLICK, playClip1);
clip2Btn.addEventListener(MouseEvent.CLICK, playClip2);
 
function initClip():void{
	ns.close();
	myVideo.attachNetStream(ns);
	myVideo.x = 111.3;
	myVideo.y = 18;
	addChild(myVideo);
}	
 
function trackGA(trackingString:String):void{
	var targetURL:URLRequest = new URLRequest("javascript:pageTracker._trackPageview('/root/"+trackingString+"');");
	sendToURL(targetURL);
}
 
 
function playClip1(e:MouseEvent):void{
	initClip();
	trackGA(FLV_CLIP1);
	ns.play(clip1);
}
 
function playClip2(e:MouseEvent):void{
	initClip();
	trackGA(FLV_CLIP2);
	ns.play(clip2);
}

This is it, actually the whole process is very simple, and sadly the support page of google analytics is not very well documented for people using actionscript 3.0, I hope I brought some light into this very important feature.

Have fun embedding those codes :)
Tiago Dias

Leave a comment

30 Comments.

  1. How would the above example change if setting this up in AS 2.0?

    Thanks in advance for a great walk thru!

  2. Simple and Great, Thanks!

  3. I normally do this using ExternalInterface (as shown in the AS2 tutorial you linked to). Do you reckon there is anything to choose from between the two methods or would you say they are equivalent?

  4. Dave
    They are both equivalent, the reason I created it this way was because I’m using part of it to track externally hosted players, in combination with a piece of sofware that the company I work for created. At the end you can use whatever you feel like comfortable with.

  5. I’m a bit of a novice with AS3 and had hacked together putting GA code on redirect pages so I could track clickthroughs for a video ad… this code is so much better.

    My question: What would you suggest to track when a user clicks the play button on the video component? That’s the missing piece between impressions and clickthroughs that I’m being asked to provide.
    thanks.

  6. Keving
    If I understood your question correctly, I would track the FLV that the clint plays, like you see on my example.

  7. This code is great… and works great. It really is much more simple than everyone makes it out to be. I have one problem though..

    I have a flash player that I want to allow anybody to embed into their page and play my video. I want to use flash event tracking to count how many times the video has been played… How can I connect to GA without each person having to embed the GA Javascript function in their html page?

    I thought you might have an idea since you are talking about how you track externally hosted players.

    Any thoughts?

  8. David, interesting I was actually waiting for someone to ask me that question :)
    Basically there is currently no possibility to use GA without the JS and get the full functionality out of it, in your case you just want to count hits. so you can easily write a serverside script (ASP, PHP) to handle the GA work, I’ve found a sweet article last week about this.
    http://www.vdgraaf.info/google-analytics-without-javascript.html

    What you can also do is use SWF Address to handle GA without exposing it to everyone ;)

  9. Great article… However, I am getting a security SandBox Violation. It says:

    SecurityError: Error #2169: The method sendToURL may not be used for browser scripting. The URL javascript:pageTracker._trackPageview(‘/main/black’); requested by xxxxxxxxxxxxxxx.swf is being ignored. If you intend to call browser script, use navigateToURL instead.
    at global/flash.net::sendToURL()
    at analyticsTest_fla::MainTimeline/sendTracking()
    at analyticsTest_fla::MainTimeline/onClickHandler()

    If I use navigateToURL I might as well use the getURL and have windows popping up everywhere….

    Any ideas?

  10. Here is a work around that helped me out:

    use:
    ExternalInterface.call(“pageTracker._trackPageview”, trackingString);

    Tested and google is picking up on it.

  11. Thanks for this solution.

    I have a question about where the Google tracking javascript code gets placed in the page that calls the SWF. On our site we have the GA script just before the …we are currently not tracking Flash events in production. I have seen a couple of blogs say that the script on these pages needs to actually be placed after the opening tag before the SWF call. Why is that? We put a test case together last night with the GA script before the tag and the events were tracked as expected.

  12. Tiago,
    I’m also trying to set this all up in AS2 and am totally lost. I’m not a flash wizard and Corban’s is not making sense to me. I really need a few instructions from the ground up. I have the GA tracking all set up but I don’t have it tracking flash properly. If you could shed some light that would be great. What and where the AS goes along with the html codes. And how to choose what is tracked in a large swf file.

    Thanks!

  13. I have a problem!
    I must to call a function in Javascript but Firebug find an arror.
    This is the code in actionscript 3:

    var targetURL:URLRequest = new URLRequest(“javascript:showMovie(’3′)”);
    sendToURL(targetURL);

    And the error is:

    showMovie is not defined

    So the code in javascript is:

    function showMovie(movie)
    {
    switch(movie)
    {

    case ’1′:

    [code...]

    case '3':
    document.getElementById('flashZone1').style.display = "none";
    document.getElementById('flashForm').style.display = "none";
    document.getElementById('flashZone2').style.display = "block";
    document.getElementById('form308').style.display = "none";
    document.getElementById('form308sw').style.display = "none";
    document.getElementById('menuZone').style.display = "block";
    break;
    }
    }

    Someone can help me?

    I'm going crazy!!! :-S

  14. Hi ! and thanks

    I just have a question :
    Where in google analytics interface can we see if it received the string ?

    thanks…
    Rycill

    PS : excuse my poor english, i’m french ;-)

  15. Hey Tiago,

    Thanks for the post.

    Question: GA recommends putting the gaTracking code before the tag, but your example has it before the . Does that matter?

    Also I was testing your demo and although GA tracked the page itself, it wasn’t tracking the clicks from within the .swf. Where could I have gone wrong from replacing UA-XXXXXX-X with my own and pushing it to a server?

  16. Whenever I try and publich your sample file I get the following errors:

    1120: Access of undefined property FLV_CLIP1.
    1120: Access of undefined property FLV_CLIP2.

    What am I doing wrong? It must be something quite stupid. Please help!

    -Travis

  17. Hi Tiago,
    I have the same problem as Travis.

    1120: Access of undefined property FLV_CLIP1.
    1120: Access of undefined property FLV_CLIP2.

    How can I fix this?

  18. Hello Tiago,
    Is there any difference in the coding if I was using an XML website?

  19. The ugg boots have long history ,popular sale all over the world.And the ccboots online store is famous as cheap sale and top quality products.for example:ugg boot on sale ,discount uggs boots ugg classic boots ,etc.

  20. Cheap UGG cardy from UGGs online store, you can get all kinds of UGG boots such as Classic Cardy. Moreover,you’ll find the sizes chart in our store! Free Shipping & Non-Tax!

  21. Cheap UGG cardy from UGGs online store, you can get all kinds of UGG boots such as Ugg Classic tall boots. Moreover,you’ll find the sizes chart in our store! Free Shipping & Non-Tax!

  22. Ana :
    Hi Tiago,
    I have the same problem as Travis.
    1120: Access of undefined property FLV_CLIP1.
    1120: Access of undefined property FLV_CLIP2.
    How can I fix this?

  23. @ana, @bunham – I have placed the strings “FLV_CLIP1″ and “FLV_CLIP2″ in quotes and it the error is no longer showing.

    I am using Flash CS4

Leave a Reply


[ Ctrl + Enter ]

Trackbacks and Pingbacks: