Flash website tracking with Google Analytics

The success of a website is evaluated by its traffic. Important data like pageviews and visitors are collected using web tracking technologies. The simplest form would be the old school visitor counter. There are many commercial web tracking services for big websites and there are also free services such as “Google Analytics(GA)“. It’s simple yet extremely powerful.

GA is a javascript based solution. Using GA in HTML is very simple. Paste in the scripts and the site is tracked instantly. To track a Flash based website is not hard either.

The first step is to insert the javascripts into the HTML page which holds the Flash file. And then call the javascript function from Flash.

There are two versions of javacripts, Legacy Tracking Code (urchin.js) and New Tracking Code (ga.js). If the HTML page uses “urchin.js”, Flash should call function “urchinTracker(your_page_name_here)” and if it uses “ga.js” call function “pageTracker._trackPageview(your_page_name_here)”.

However, calling directly to GA’s functions is not the best practice. First, the page name does not contain the full URL address. For example, if a swf file sits in “about.html”, if calling GA’s functions directly in Flash, the record shows up just as “about”, which give no clue where the page came from. But a full record triggered in HTML will appear something like “www.yourdomain.com/your_folder/about.html”. Second, if GA decided to change the function’s name, Flash will call a non-existant function, trackings are lost and it will also generate a javascript error.

A wrapper javascript function can solve all these problems. Here’s a sample:

function track(pageName){

        var url=window.location.href;
        pageName=url+”?”+pageName;//this gives the full URL address
        // urchinTracker(pageName); //this is for urchin
        pageTracker._trackPageview(pageName) // this is for new tracking code

    }

With this wrapper function, Flash calls “track( your_page_name_here)” instead of GA’s functions. When a new version of GA comes out, only “track” function needs to be changed and the Flash file does not need to be republished.

Another issue need to be covered is how to call javascript functions from Flash. The moden approach is to use “ExternalInterface.call”, for example:

ExternalInterval.call(”track”, “your_page_name_here”);

More traditional functions like getURL in AS2 and navigateToURL in AS3 also work:

getURL(”javascript:track(”+your _page_name_here+”)”); //AS2
navigateToURL(new URLRequest(”javascript:track(”+your _page_name_here+”)”)); //AS3

Which method to use will lead to a long discussion of comparing ExternalInterface and getURL/navigateToURL. Here’s an article to dive into and this one too.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License