Saturday, September 22, 2012

Setting up Google Analytics tracking for cross domain, dynamically generated iframe content

There are barely any websites that don't use Google Analytics tracking to monitor activities on their site. I don't have to explain what you can achieve with Google Analytics tracking, however the purpose of this post is to share my experience with setting up tracking for cross domain dynamically loaded iFrame content. 

Let's say you have a page that loads content in iFrame, from another domain, now you want to track the user flow between your main site and the page you are loading in iFrame. 

Assuming you are using async Google Analytics script, update Google Analytics script, on the main site as shown below :

_gaq.push(['_setAccount', 'UA-XXXXXX-X']);
_gaq.push(['_setAllowLinker', true]);

"_gaq.push(['_setAllowLinker', true]); " is responsible for enabling cross domain tracking. 

On the site containing iFrame content i.e on, update Google Analytics script as shown below

_gaq.push(['_setAccount', 'UA-XXXXXX-X']);
_gaq.push(['_setAllowLinker', true]); 
_gaq.push(['_setDomainName', 'none']);

So, far we have enabled cross domain tracking between two sites, next step will be to send cookie information from one site to another via URL. 

Assuming iFrame is dynamically loaded via javascript, we can add cookie information to iFrame URL as shown below

var iframesLoadEvent = self.setInterval(function() {
var iframes = $("iframe[id*='easyXDM']");

if(iframes.length > 0) {


//Google code to append cookie information to the URL
_gaq.push(function() {
var pageTracker = _gat._getTrackerByName();
var iframe = iframes[0]; 
//Get the original iframe URL
var iFrameUrl = iframe.src;  
//Ask Google Analytics to add cookie information to the url and update iFrame with the new URL
iframe.src = pageTracker._getLinkerUrl(iFrameUrl);


Even though all this looks very simple once sorted, it took me days to sort it out.

Note : Internet Explorer does not allow third party cookies, which means even if you have set up cross domain tracking properly, it will work on Firefox, Safari and Chrome, but not in Internet Explorer.

I've overcome this problem by adding a p3p header for the response from site retrieved in iFrame. For example add following P3P header to response page from the site


No comments:

Post a Comment