Permanent links in Flex and track them with Google Analytics

June 30th, 2009

The purpose of this tutorial is to recreate the browsing experience similar to HTML, so you can save / share links and track clicks through sections of your site.

I first created a very simple application, having 3 sections: Home, Events and Contact:

The directory structure

The application is organized in Views using ViewStack

CODE:

<mx:ViewStack id=”views” horizontalCenter=”0″ verticalCenter=”0″>

<views:home id=”home” label=”Home” showEffect=”{fadeIn}” hideEffect=”{fadeOut}” />

<views:events id=”events” label=”Events” showEffect=”{fadeIn}” hideEffect=”{fadeOut}” />

<views:contact id=”contact” label=”Contact” showEffect=”{fadeIn}” hideEffect=”{fadeOut}” />

</mx:ViewStack>

Every  view being placed in com/views/* , and all are components having the same structure:

CODE:

<mx:Canvas xmlns:mx=”http://www.adobe.com/2006/mxml” width=”400″ height=”300″>

<mx:VBox>

<mx:Label text=”Home page” />

<mx:TextArea htmlText=”Lorem ipsum”

editable=”false” borderThickness=”0″ condenseWhite=”true” backgroundAlpha=”0″ focusRoundedCorners=”0″ focusThickness=”0″

verticalScrollPolicy=”auto” horizontalScrollPolicy=”off”/>

</mx:VBox>

</mx:Canvas>

For menu display I used the very intuitive LinkBar that extracts labels from views inside ViewStack (great!)

CODE:

<mx:LinkBar dataProvider=”views” top=”10″ horizontalCenter=”0″/>

And that’s it for our simple application setup.

Preview what we have so far:

Ok it all works ok now, but we want, to send somebody directly to our events page. Simple! For that we will have to use the BrowserManager so we can add trailing variables to our page link. They will be pairs variable=value after a # character.

The steps are very simple, when we first load our application we check the variables, if any, at the end of our url and load the specified view. And during our application is running we update the url every time we change views, and update views every time we spot a url change (so we can also handle the browser’s back button).

Note! This makes use of the history.js script, make sure it’s included in your index.template.html file.

CODE:

<mx:Script>

<![CDATA[

// browser

import mx.events.BrowserChangeEvent;

import mx.managers.IBrowserManager;

import mx.managers.BrowserManager;

import mx.utils.URLUtil;

private var bm:IBrowserManager

protected function init() : void {

//get an instance of the browser manager

bm = BrowserManager.getInstance();

//initialize the browser manager

bm.init();

//set initial values based on url parameters

updateContent();

//add event listeners to handle back/forward browser buttons

bm.addEventListener( BrowserChangeEvent.BROWSER_URL_CHANGE,onURLChange );

}

private function updateContent():void

{

//convert url parameters to an actionscript object

var o:Object = URLUtil.stringToObject(bm.fragment);

//set the selected view

var p : String = (o.p != null)?o.p:"home";

Application.application.views.selectedChild = getViewsChildById(p);

}

private function onURLChange( event : BrowserChangeEvent ):void

{

//call update values based on change url

updateContent();

}

public function updateURL():void

{

//update URL fragment

var page : String = Application.application.views.selectedChild.toString().split(".").pop().toString();

bm.setFragment( "p=" + page );

}

private static function getViewsChildById(str : String):Object {

for each (var child : Object in Application.application.views.getChildren()) {

if (child.id == str) {

return child;

}

}

return null;

}

]]>

</mx:Script>

We store a browser manager instance into out IBrowserManager variable. Upon applicationComplete event we launch init(), initializing the browser manager, updating to selected view, and hooking a BROWSER_URL_CHANGE event to update views every time a url is change or browser’s Back, Forward button is pressed.

The pairs stored at the end of the url can be extracted from BrowserManager’s .fragment value. For example, I used the variable p to store the view name. So, for example the events view will have a link like http://localhost/…/permaLink.html#p=events

Since the value from fragment  is a string, I also created a helper function that extracts the view child by specifying it’s name getViewsChildById(str:String) that returns the object representing that view.

Next step is to put a handler on ViewStack change event , change=”updateURL()” so we will update the browser’s url every time a view is changed inside our application.

The updateUrl() simply reads the current ViewStack selectedChild and updates BrowserManager’s fragment variable.

CODE:

var page : String = Application.application.views.selectedChild.toString().split(“.”).pop().toString();

bm.setFragment( “p=” + page );

That’s it. Simple, right? Now when we click on events our url will like this:

Preview (note the p=value pair at the ending of your url)

Now our next task is to track this clicks with Google Analytics. Practically our Flex application behaves now like a Ajax application. So we just have to include our Google Analytics code in the <head> tag of our output html.

You can do this by modifying the html-template/index.template.html file.

CODE:

<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”>

try {

var pageTracker = _gat._getTracker(“put your tracker ID here”);

pageTracker._trackPageview();

} catch(err) {}

</script>

</head>

And when we update the url’s we should tell Google Analytics that we changed that page. For this purpose we have the function pageTracker._trackPageview(pageName).

So we will simply add a call to this Javascript function, using the Flex’s ExternalInterface.call , in the updateUrl function:

CODE:

ExternalInterface.call(‘pageTracker._trackPageview’,‘#’+bm.fragment);

So now we can share permanent links to views of our applications, we can track landing / exit pages, all trafic statistics with Google Analytics.

Thank you.

You can view the application in action here.

You can download sources here: permalink

Flex Friendly URLs and Tracking in Google Analytics

June 17th, 2009

Hey,

I recently posted a tutorial to Transylvania Flex Group on adobe.com

http://groups.adobe.com/posts/6bca8cb2e9

You can learn how to create permanent links with Flex Applications and Track dynamic clicks with Google Analytics.