Thursday, January 13, 2011

Bypass specific IP from rendering google analytics code

To bypass specific IP from rendering google analytics code, follow the following steps.



  1. List the IP which you wants to bypass from rendering into your web application, and add in web.config file

    e.g. <add key="ByPassUrl" value="101.101.101.100"/>


  2. Create a Usercontrol and named "GoogleAnalytics.ascx" replace your google analytics code with "<google analytics code here>".

    <%@Control Language="C#" AutoEventWireup="true" CodeFile="GoogleAnalytics.ascx.cs"
    Inherits="Include_GoogleAnalytics"%>


    <script type="text/javascript">


    <% if (ConfigurationManager.AppSettings["showGoogleAnalytics"] == "True") {%>


    <% if (!strByPassUrl.Contains(requestUrl)) {%>


    var _gaq = _gaq || [];


    _gaq.push(['_setAccount', '<google analytics code here>']);


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


     


  3. Declare following 2 public variable in "GoogleAnalytics.ascx.cs" file

    public string requestUrl = HttpContext.Current.Request.UserHostAddress.ToString();
    public
    string strByPassUrl = clsCommon.value("ByPassUrl");


  4. Add "GoogleAnalytics" user control in master page of the application within <Head></Head> tag.

    <head runat="server">


    <uc2:GoogleAnalytics ID="GoogleAnalytics1" runat="server"/>


    </head>


Note :- 1) Before Copying Google analytics code verify with google analytics script, provided in google analytics account.

2) check if "showGoogleAnalytics" key is present in web.config file.

No comments:

Post a Comment