lostpencil 阅读(1394) 评论(1)

Introduction

google_analytics_logo.gif

If you have used Google Analytics to monitor and analyze traffic on a website, you were most likely impressed with the ability it gave you to understand the nature of visits to and exits from the site, learn how visitors found it, discover how much time people spent there, et cetera. Recently, the Google Analytics team announced1 the availability of an open source, native AS3 API that enables you to utilize Google Analytics (GA) tracking from within your RIA.

This article introduces the newly available Google Analytics Tracking for Flash API (gaforflash). I'll cover where to obtain and install the necessary software, introduce basic concepts and terminology, show you how to use it in both component form and native code form, cover the primary methods for reporting activity inside a Flex-based RIA, and talk a bit about limitations and best practices.

The examples that accompany this article were compiled and tested against gaforflash version 1.0.1.319. There are 2 examples with full source code included. They can be viewed here: example 1 (source), example 2 (source). Also note that this article covers using gaforflash within the Adobe Flex environment (I used Flex Builder 3, build 3.0.2 to construct the examples). See the gaforflash project2 website for information regarding its use in the Flash authoring tool.

Downloading Google Analytics Tracking for Flash

Google Analytics Tracking for Flash is an open source project. After making event tracking available via the new GA Javascript library (ga.js), Google realized the need for a native AS3 implementation. Google Analytics Specialist Nick Mihailovski described the project's genesis: “We first got a group of 3rd party developers together to help us understand the difficulties they faced with tracking Flash. At the same time, we worked with a team of Adobe engineers to build the foundation of the GA tracking capabilities. Once at an alpha stage Zwetan Kjukov approached us to further develop the code. He brought Marc Alcaraz onboard and together, took the code to new heights. A huge amount of work was put in to re architecting the system to work in local/remote, embedded/disributed, Flash/Flex environments. The entire code base got new unit tests and an amazing ANT build was put together to simplify pushing new builds. Nov 17th [2008] we launched at MAX as an open source project.”

The website is located at . From there, you can access the source code, read tutorials and ongoing discussions in the developer group, and download compiled SWCs.

ga1.png

The SWCs are ZIP archived and can be found under the downloads section of the site. The easiest way to include them in your project is to copy the analytics.swc file (contained in the archive's lib folder) to your project's lib folder.

Figure 1 (right): The GA analytics.swc placed in a Flex project's lib folder

Page Views vs. Events

The gaforflash API supports the transmission of two types of tracking information: pageviews and events (support for a third type—e-commerce transactions—is on the roadmap). While you may be tempted to just send events inside your event-driven RIA, there are in fact good reasons to use both.

You'll likely want to use pageview tracking in your RIA when you want to understand how a person navigates through your application. On the Google Analytics Dashboard, you'll be able to then learn which views inside your RIA result in the most exits and take advantage of the multitude of analysis tools that are only available with pageview tracking. The next section demonstrates tracking pageviews inside a Flex Accordion control.

Events should be used when you want to track information not relating to the user flow within your application. Event tracking allows four arguments to be recorded. The section below entitled “Event Tracking” demonstrates using Event tracking to record events involving the loading and playing of a video.

Tracking Page Views

Granted, the term “page view” is a bit of a misnomer inside a Rich Internet Application. But in the world of Google Analytics (which is most often used for HTML page tracking), the pageview is the primary metric around which most of the analysis tools are based. It makes sense to accept the term's inaccuracy and use them to your advantage.

The following example illustrates using the gaforflash code in component form, sending pageview tracking from inside a Flex Accordion component and examining the pageviews on the Google Analytics Dashboard.

1 <?xml version="1.0" encoding="utf-8"?>

2 <!--

3 Example 1. Embed the gaforflash component,

4 demonstrate pageview tracking.

5 Tested against gaforflash-1.0.1.319

6 -->

7 <mx:Application xmlns:mx=""

8 layout="absolute"

9 xmlns:ga4flash="ponents.*"

10 addedToStage="trackInitialView()">

11

12 <ga4flash:FlexTracker

13 id="tracker"

14 account="UA-111-222"

15 visualDebug="true"

16 mode="AS3"

17 />

18

19 <mx:Script>

20 <![CDATA[

21 public function trackInitialView():void

22 {

23 tracker.debug.minimizedOnStart = true;

24 tracker.trackPageview("/pane1");

25 }

26 ]]>

27 </mx:Script>

28

29 <mx:Accordion x="31" y="43" width="380" height="423"

30 change="tracker.trackPageview('/pane' + String(event.newIndex+1));">

31 <mx:Canvas label="Pane 1" width="100%" height="100%">

32 <mx:Text text="Welcome to Pane 1."/>

33 </mx:Canvas>

34 <mx:Canvas label="Pane 2" width="100%" height="100%">

35 <mx:Text text="Benvenuti a Pane 2."/>

36 </mx:Canvas>

37 <mx:Canvas label="Pane 3" width="100%" height="100%">

38 <mx:Text text="Bienvenue à Pane 3!"/>

39 </mx:Canvas>

40 </mx:Accordion>

41

42 </mx:Application>

Check out line 12. It shows the FlexTracker component added to a Flex Application in declarative form. Here's a breakdown of the properties:

  • id: this property allows the FlexTracker to be referenced elsewhere (line 24 for example).
  • account: this property holds the Google Analytics profile that the tracking is being sent for. This will be a profile that you (or your clients) control.
  • visualDebug: this property puts the gaforflash API in debug mode. No events are sent to the GA servers, instead they are logged in a debugging window that's a child of the stage.
  • mode: this value must be either AS3 or Bridge. Bridge mode should be used when your RIA is embedded within web pages that have GA Tracking enabled. This mode allows your RIA to adapt when, for instance, the GA profile for a site is changed. Bridge mode is accomplished through the use of ExternalInterface, so it's important for your RIA's embed code to specify the correct allowScriptAccess parameter. AS3 mode should be used in the counter-situation: instances where you do not control the HTML pages on which your RIA is included (for instance widgets copied to ), or you do control the HTML pages but there is no GA tracking enabled on them. See the gaforflash site3 for more information regarding the use of the mode property.

Tracking pageviews is accomplished using the trackPageview method of the FlexTracker component. In this example, those calls are on lines 24 & 30. The sole parameter to this method is the “URL” of the pageview, which of course isn't a URL but rather the name of a logical view inside the RIA, in this example the Accordion pane that is opened.

Example1 mimics the functionality of a website in that the three exposed Canvas components represent the three principal “views”, sending pageview tracking each time the Accordion's active pane changes. Note that because the initial view of the Accordion doesn't register a change event, I send an initial pageview on line 24.

Alt Text
Figure 2: Example1, the Accordion-based pageview example

In this example, since the visualDebug property is set to true (line 15) no data is actually sent to the GA servers. Instead it's captured in the logging window shown at the bottom of the page (see Figure 2) which allows you to see the three pageview events that would have been sent as the different panes are clicked. The visualDebug property is a good way to ensure you have your analytics code in the state you expect before you begin sending data to the GA servers.

Tracking pageviews in this manner allows me to use the GA Dashboard to understand how people interacted with my example application.

Alt Text
Figure 3: Viewing the Pageviews data on the Google Analytics Dashboard

Note that any GA profile can receive pageview tracking from the gaforflash API (unlike Event Tracking which requires that your profile be white-listed by Google before you can see the data).

Event Tracking

Event Tracking is best used for monitoring activity inside your RIA that's not related to navigation. The following example sends GA Event Tracking data as a viewer interacts with a video component. Also, in order to illustrate the API's class constructors, care was taken to use no components in declarative MXML.


1 <?xml version="1.0" encoding="utf-8"?>

2 <!--

3 Example 2. Use gaforflash's classes,

4 demonstrate event tracking.

5 Tested against gaforflash-1.0.1.319

6 -->

7 <mx:Application xmlns:mx=""

8 layout="absolute" addedToStage="initExample2()">

9

10 <mx:Script>

11 <![CDATA[

12 import mx.events.MetadataEvent;

13 import mx.controls.Button;

14 import mx.events.VideoEvent;

15 import mx.controls.VideoDisplay;

16 import mx.containers.Panel;

17 import com.google.analytics.GATracker;

18

19 private var tracker:GATracker;

20 private var readyTime:Number;

21 private var video:VideoDisplay;

22

23 public function initExample2():void

24 {

25 tracker = new GATracker(this, "UA-111-222", "AS3", true);

26

27 //build video UI

28 var panel:Panel = new Panel();

29 panel.title = "Example 2";

30 panel.setStyle("horizontalAlign", "center");

31 panel.x = 20;

32 panel.y = 40;

33 panel.width = 545;

34 panel.height = 372;

35 this.addChild(panel);

36 video = new VideoDisplay();

37 video.autoPlay = true;

38 video.width = 525;

39 video.height = 300;

40 video.autoRewind = false;

41 video.addEventListener(VideoEvent.READY, handleReady);

42 video.addEventListener(PLETE, handleComplete);

43 panel.addChild(video);

44 var button:Button = new Button();

45 button.label = "Pause";

46 button.addEventListener(MouseEvent.CLICK, handlePause);

47 panel.addChild(button);

48

49 readyTime = new Date().time;

50 video.source = "";

51 }

52

53 public function handleReady(event:Event):void

54 {

55 // calculate time (in milliseconds) in which

56 // the video was ready to play

57 readyTime = new Date().time - readyTime;

58 tracker.trackEvent("Videos", "ReadyTime", "Video1", readyTime);

59 }

60

61 public function handleComplete(event:Event):void

62 {

63 tracker.trackEvent("Videos", "Completed", "Video1");

64 }

65

66 public function handlePause(event:MouseEvent):void

67 {

68 var button:Button = event.target as Button;

69 if (button.label == "Pause") {

70 video.stop();

71 button.label = "Resume";

72 tracker.trackEvent("Videos", "Paused", "Video1");

73 } else {

74 video.play();

75 button.label = "Pause";

76 tracker.trackEvent("Videos", "Resumed", "Video1");

77 }

78 }

79

80 ]]>

81 </mx:Script>

82

83 </mx:Application>

Line 25 initializes a GATracker. The first parameter to the constructor can be any DisplayObject that is on the display list, in the example it's simply the mx:Application. The second parameter is your GA Profile, the third parameter is the mode property—either Bridge or AS3—as discussed in the previous section. The final parameter sets the visualDebug property which was also described in the previous section.

This example tracks four events:

  1. On line 63, a GA Tracking Event is sent when the video component completes playing.
  2. On lines 72 and 76, a Tracking Event is sent when the video is paused and resumed.
  3. On line 58, the elapsed time of when the video begins loading to when it is ready to be played is sent in an Event.

The GATracker.trackEvent method is responsible for sending tracking events. The method takes four parameters:

  • category: a string representing groups of events.
  • action: a string that is paired with each category and is typically used to track activities.
  • label: an optional string that provides additional scoping to the category/action pairing.
  • value: an optional non-negative integer that associates numerical data with a tracking event.

The example provided above illustrates one common use of the category/action assignment; whereby “Videos” is the category, the action is the activity I'm interested in and the label (“Video1”) serves to narrow the category even further (imagine other videos labeled Video2 through Video5). The GA Dashboard allows you to slice and dice Tracking Events by these dimensions in various ways. For instance, I can view all “Completed” actions to see which labels (Videos1 through 5) resulted in the most complete views. For more information on classifying your categories, actions and labels, see the Google “Tracking Events” website4.

Line 58 shows the passing of the optional fourth value parameter to the trackEvent method. On the GA Dashboard, the values for the example ReadyTime action will both summed and averaged (see Figure 5).

Alt Text
Figure 4: Example 2, passing Tracking Events resulting from the interaction with a video

Once events begin flowing into your GA Profile, you'll be able to view them using the GA Dashboard.

Alt Text
Figure 5: Viewing events from Example 2 on the Google Analytics Dashboard

Notice the ReadyTime action in Figure 5. We can learn from this that, for the four visits on this date, it took on average 307 milliseconds for the video to be ready to play.

Implementation Notes

The Sprout software team has successfully integrated gaforflash into our architecture and now our clients have access to state-of-the-art traffic and usability analysis of their campaigns. Here are some implementation notes based on our experiences that you might find useful.

  • Cache a GATracker instance for reuse instead of instantiating a new instance for each tracking event.
  • Integrate pageview tracking into the controllers of your preferred MVC model.
  • Involve your clients (and/or other stakeholders) early in determining the exact business analysis your implementation should allow.
  • There is a 500 event limit on events sent per session. Consider adding a static event counter, and send an “event overflow” event after the 499th event in order to know the number of sessions that are underreporting.
  • There is some latency (as little as one hour, as much as eight) from when the event is sent to when it appears in the GA Dashboard. And the visualDebug property can really interfere with your RIA's user interface. Consider logging event and pageview tracking to a Firebug console or other browser debugging platform.

Conclusion

Google Analytics Tracking for Flash offers unprecedented analysis capabilities for Rich Internet Applications. Using pageview tracking for user-flow analysis can help you understand the strengths and weaknesses of your interface design. Using event tracking can help you combine activity interactions with categories and numerical information.

Source Files

gaforflash-example1.zip gaforflash-example2.zip

Read more from Matthew McNeely. Matthew 
McNeely's Atom feed


发表评论
切换编辑模式