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

Thursday, May 19, 2011

Startup JavaScript Code from Content Page to Master Page

Let say, you have Master and Content pages and you want to add some JavaScript code from your Content pages that would run when the page is loaded. Content pages do not have the HTML elements like body tag to add your script on its onload event.

For this, you can use RegisterStartupScript method. Add the following code to your Content Page code behind Page_Load Event:

protected void Page_Load(object sender, EventArgs e)
{
Type type = GetType();
const string scriptName = "alertPopup";
if (!ClientScript.IsStartupScriptRegistered(type,scriptName))
{
ClientScript.RegisterStartupScript(type, scriptName, "alert('Hello World!')", true);
}

}
Happy Programming!!