Tuesday, May 24, 2011

Redirects handled by Google Analytics

Google Analytics won't track a visit to a page unless that page runs the analytics tracking code. Although, there are at least 2 ways to track the redirects:
-Tracking a redirect using 301 redirect.
-Tracking a redirect using a JavaScript redirect.

In both instances, make sure the directory actually exists as a file (/it/growthmodel.aspx). I always use the JavaScript redirect so, let's talk about it:
Let say, you have a pdf file (growthmodel.pdf), you want to post it online and also want to count the number of visitors and their behaviours. For this, create a page growthmodel.aspx under the /it directory and redirect this page to pdf file using javascript redirect. Put the below code at growthmodel.aspx page:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript"
>

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

(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ?
'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>

</head>
<body onLoad="_gaq.push(['_trackEvent', 'category', 'action', 'opt_label'])">
<script type="text/javascript"
>

function redirect()
{
window.location =
"/growthmodel.pdf"
}

var temp = setInterval("redirect()", 1000);

</script>
</body>
</html>

setInterval=> 1000 so that tracking doesn't get missed.
'UA-XXXXXX-X' => please replace xxxx with your actual analytics account number.

Happy Programming!!

No comments:

Post a Comment

Highly Appreciated your comments