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 www.mainpage.com that loads content in iFrame, from another domain www.contentforiframe.com, 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 www.mainpage.com as shown below :

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


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

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

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

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) {

window.clearInterval(iframesLoadEvent);

//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);
});

}},10);


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 www.contentforiframe.com


P3P:
CP="NOI DEV PSA PSD IVA IVD OTP OUR IND OTC"






No comments:

Post a Comment