Sunday, May 17, 2009

Google Analytics is a web traffic and demographics reporting service provided free of charge by Google. Google Analytics functionality can be added to any web site by setting up an account and adding a snippet of JavaScript to every page within the web site. Once configured you can see all types of statistics such as how users were referred to your site, number of hits per page, where your users are located geographically, what types of browsers and OS they are using, and much more.

This post outlines how to add Google Analytics to a SharePoint Publishing site. You must have edit rights for all site Master Pages. Google Analytics can complement the Usage Reports available to Site Collection Administrators and Search Term Reports available to Shared Service Provider Administrators. Analytics can also be used to provide read-only access to users who do not have administrative rights on the SharePoint site but whose job function might benefit from access to detailed site usage data.

1. Setup a Google Analytics Account for the Site

1-1. Click here to register your site for Google Analytics. Note that the web site you are registering can be a public, intranet, or private company site. You can register the site with a new or existing Google account, and you have the option at any time to allow other Google accounts to act as administrator or have read-only rights to the Analytics reports.

1-2.  After you have registered and created a profile for your site, get the JavaScript code for the site. These 2 help pages on Google explain how to find the JavaScript code and add it to your site pages (don’t add any JavaScript to your site pages yet):

Where can I find my tracking code from within my Google Analytics account?

How do I add tracking code to my website?

TrackingCode

1-3. Open your site in a browser, and evaluate the page titles displayed in the browser title bar and tabs as you click through the site. Do your pages have meaningful page titles that are unique for each page? If not, you should correct this before adding Google Analytics to your site. Otherwise you will not be able to differentiate the traffic for each page.

UniquePageTitles

2. Configure Google Analytics to Report on Search Terms Entered by Users

Google Analytics provides a quick and easy way to track the search terms being entered by users of your SharePoint Publishing site. Although SharePoint can be configured to track search terms, it requires additional configuration by the Farm Administrator and the search terms are only visible to the Shared Service Provider Administrators. To fully take advantage of SharePoint search functionality such as Best Bets, Site Collection Administrators and Content Authors need to know what search terms are being entered by users. Having to manually request the Shared Service Provider deliver this information on an ongoing basis is a waste of resources when you can easily configure Google Analytics to track it at no expense.

Assuming you are using a SharePoint search site and have not altered any of the defaults or code for search queries, all SharePoint search term queries are submitted using the parameter name k. It’s important that you are not using the parameter name k for any of your forms or custom development running within the site. To configure Google Analytics to track the search term queries, you need to configure the Site Search settings in the Google Analytics site profile. See the Google Analytics Help article How do I set up Site Search for my profile? for details of how to find and configure the Site Search settings.

After you have setup Site Search, your settings should look like the screenshot below:

image

3. Add Tracking Code to the Site Master Pages

The next step is to add the JavaScript tracking code obtained in step 1-2 to your site Master Pages. As described in the Google references in section 1, you need to add the tracking code to the end of each site Master page, just prior to the </body> tag. How you do this depends on which of the 3 cases below your site development and publishing processes fall into:

3-1. If the site is production only, meaning you don’t have a development, test, or staging environment, and the changes you make to the Master Pages are immediately applied to production, then just paste the JavaScript into the master pages prior to the </body> tag, save, and publish.

3-2. If the site has pre-production environments such as development, test, or staging, and site Master Pages are maintained as content specific to each environment and solution files or content deployment are not used to publish the same Master Page to each environment, then you can still copy-paste tracking code to the production environment only.

3-3a. If the site has pre-production environments such as development, test, or stage, and the same version of each Master Page is published to each environment with solution files or content deployment, then you will want to setup a mechanism to prevent having your pre-production traffic logged as production traffic. Otherwise the clicks generated in your pre-production environments by developers and testers will show up in the reports and bias the interpretations of site traffic, what pages are most popular, etc.

If your site falls into case 3-3, you have 2 choices for filtering out the pre-production clicks from your Google Analytics reports. If you know the IP addresses or range of IP addresses for all users who will access the pre-production sites, and you don’t need to track those users when they access your production site, then you can exclude specific IP addresses or a range of IP addresses in the Analytics Settings. If you cannot use IP filtering for all pre-production users, or if you need to capture the IP addresses of those users in production, then you can add code to your Master Pages or create an ASP.NET User Control and include it in your Master Pages to conditionally render the tracking code.

3-3b. Create a User Control to Conditionally Render the Tracking Code

If your situation falls into category 3-1 or 3-2 above, then you can skip this section. If your site falls into case 3-3 and you need to conditionally include or exclude the JavaScript tracking code depending which environment you are running in, then you can achieve this in a reusable fashion with an ASP.NET User Control.

3-3-1. Add an AppSetting configuration property to Web.config or any config file readable by the ASP.NET ConfigurationManager which sets a flag to display or hide the tracking code in the environment in which the code is running. This flag would be set to true only in the production environment, or in pre-production environments when testing that the code is included correctly.

<add key="IncludeGoogleAnalytics" value="false" />

3-3-2. Create a user control called GoogleAnalytics.ascx and deploy to _controlTemplates. The code below does not display the tracking code when the flag from step 3-3-1 is set to false or the current page is in edit mode. This is to prevent tracking of these requests and also to limit the possibility of JavaScript clashes when editing publishing pages:

<%@ Control Language="C#" AutoEventWireup="true" 
    CodeBehind="GoogleAnalytics.ascx.cs" 
    Inherits="GoogleAnalytics" %>
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + 
    "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("YOUR_SITE_TRACKER_ID");
pageTracker._trackPageview();
} catch(err) {}</script>

public partial class GoogleAnalytics : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // FormMode publishing states: Display, Edit, Invalid, New
        this.Visible = ConfigurationManager.AppSettings["IncludeGoogleAnalytics"] == "true" &&
            (SPContext.Current.FormContext.FormMode != SPControlMode.Edit &&
             SPContext.Current.FormContext.FormMode != SPControlMode.New);
    }
}

3-3-3. Include the new user control at the end of each Master Page.

<%@ Register TagPrefix="Google" TagName="GoogleAnalytics" 
    src="~/_controltemplates/YOURPATH/GoogleAnalytics.ascx" %>
    <Google:GoogleAnalytics Visible="false" runat="server" />    
</body>
</html>

4. Using Google Analytics

After your have published the Google Analytics tracking code and confirmed all pages in your production environment are including the JavaScript tracking code, then you can start to track your site reports in Google Analytics. Analytics currently updates once each night for the previous day’s traffic, and after you deploy the code for the first time it will take 12-24 hours for data to start showing up in the Analytics Dashboard.

In addition to the Dashboard displayed when you click to view the Site Reports in Google Analytics, I have found the 4 screens listed below to be very useful in understanding how users are accessing the site. The navigation path required to reach each screen are pictured as a reference for how to access these reports.

4-1. Content by Title


image

4-2. Map Overlay


image

4-3. Site Search Terms

image

4-4. Browsers and OS

image

Bookmark and Share  Comments [25] | Permalink | GoogleAnalytics | SharePoint
Tuesday, May 19, 2009 7:43:08 AM (Mountain Standard Time, UTC-07:00)
Mike, thanks for posting this excellent step-by-step guide; really great content!
Wednesday, May 27, 2009 2:52:10 PM (Mountain Standard Time, UTC-07:00)
Mike - great post!

Quick question:

For category 3, could an additional alternative be to wrap a bit of javascript code around the google tracking call to only fire if the URL contains your production domain name thereby not firing in dev, staging etc?

Damon
Wednesday, May 27, 2009 6:34:17 PM (Mountain Standard Time, UTC-07:00)
Damon,
Excellent tip, I had not thought of modifying the script. One of the nice things about having it in a control is you can turn it on and off to test the inclusion of analytics prior to it going into production without having to change anything in the code. The important thing is to get Analytics hooked up, it's a great complement to SharePoint and I think easier to use then the Usage Reports and Shared Service Provider Search reports.
Friday, May 29, 2009 7:12:59 AM (Mountain Standard Time, UTC-07:00)
Hi Mike, I found your article very useful, thanks for posting it.

In VS08, I had to make 1 change and that was:

ConfigurationManager.AppSettings["IncludeGoogleAnalytics"] && (SPContext...
to
ConfigurationManager.AppSettings["IncludeGoogleAnalytics"] == "true" && (SPContext...

to avoid build errors.

I do have one other issue and I hope you may know what it causing it as I cannot find information anywhere. When I run my control, SPContext.Current.FormContext.FormMode always returns as "Invalid" which is the default value. This happens regardless if I am in display, edit or new mode. Any idea why this might be happening?

P.S. It might also be helpful to know that if you have not modified a masterpage through SharePoint Designer, you can add your control to the one the default.masterpage located at C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\GLOBAL on the hosting server and it appears to apply it to all pages.
Saturday, May 30, 2009 3:56:31 PM (Mountain Standard Time, UTC-07:00)
Joshua,
A few points in response to your great feedback:

1. Thanks for the code correction, I left out the boolean string check when formatting it for the blog and have corrected the code in the post.

2. A value of Invalid for SPContext.Current.FormContext.FormMode usually indicates the page does not reside in the content database and would not have dynamic web part support. For example if you add the control mode to a filesystem or Search Center site page then I think the mode will always be Invalid. This does not mean there is a problem, "Not Applicable" is probably a better way to think of it.

3. Your point about modifying default.masterpage is interesting as that page would be used for many of the pages displayed and managed by SharePoint for team site and administrative functionality. The fact that this page resides on the filesystem is probably why you are seeing the value of Invalid for FormMode as it's a filesystem page and thus not going to support adding dynamic web parts as a content page would. Thanks for the tip!

Monday, June 15, 2009 8:28:49 AM (Mountain Standard Time, UTC-07:00)
Mike,
Thanks for the information. I have been so far unsuccessful at integrating GA with our Intranet. Does GA work without anonymous access? We are using SharePoint services 3, not MOSS. The code is on each master page in use, and I can verify by looking at the source of each rendered page, but on the GA dashboard, it states the code is not installed...Any help is appreciated.
Monday, June 15, 2009 8:06:38 PM (Mountain Standard Time, UTC-07:00)
Josh,
It can take a day or two for GA hits to start showing up in the reports. Assuming you've already waited a few days, you might want to double-check you are using the correct tracking code. Log into GA, click on the profile settings for the site in question, and then click the "Check Status" link. Compare the Web Property ID shown in the top section and the tracking code JavaScript in the lower pane and make sure they match. GA would not be impacted by the authentication in use on your site since the JavaScript makes requests back to Google from the html page and that outgoing path is not impacted. Also, check that your JavaScript is 100% correct. If you are a developer, you can try running the JavaScript code on your own machine or a development machine, and then see if those hits show up in GA.
Tuesday, June 16, 2009 5:38:57 AM (Mountain Standard Time, UTC-07:00)
I'm not a developer, just a humble admin ;), the code matches verbatim, and I've also tried moving it to the header section, still no joy. I have the GA code on other sites, it's only SharePoint that is not working. Are there any hooks I can add to the code to get it to display an error, or event trace?

*UPDATE*
By moving the GA code from the body, to the HEAD section, GA began recognizing the code...Thanks!
Thursday, July 09, 2009 9:22:03 AM (Mountain Standard Time, UTC-07:00)
Hi Mike \ Joshua,
Please guide me for setting up share point intranet for Google analytic.

(1) we have local company intranet,not accessible outside of company local intranet.
i.e http://myintranet
(2) i kept Google analytic JavaScript code at
C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\GLOBAL\default.master
(3) i kept this code at first try above </body> tag and at above </head> tag.But in both case it do not work.
(3) what should i put in Google analytic ,
website URL ?? (if i put http://myintranet will it be ok or http://0000.0000.0000.0000 will be OK ?? )
Default page ?? (in my case it is default.aspx (/default.aspx))
(4) what is the difference between,
==================
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' originalAttribute="src" originalPath="" + gaJsHost + "google-analytics.com/ga.js" type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
var pageTracker = _gat._getTracker("UA-xxxxxxx-x");
pageTracker._initData();
pageTracker._trackPageview();
</script>

================

and

===============
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("UA-xxxxxxx-x");
pageTracker._setDomainName("none");
pageTracker._initData();
pageTracker._trackPageview();
} catch(err) {}</script>

=============

(5) i checked status of my code in google apps by clicking (Tracking Not Installed ( Check Status [?] )) but it shows following message ..
(Last checked: Jul 9, 2009 9:19:35 AM )
The Google Analytics tracking code has not been detected on your website's home page. For Analytics to function, you or your web administrator must add the code to each page of your website.

Is there is any way to things done ???

Arkesh
Arkesh
Thursday, July 09, 2009 4:36:57 PM (Mountain Standard Time, UTC-07:00)
Arkesh,
By default Google Analytics uses a domain name setting of "auto" which requires a fully qualified domain name to work. However you can make use of a GA JavaScript function to set the domain name to "none" prior to calling trackPageView and that should cause data to start showing up in GA when users access http:\\intranet. Here's how it would look:

pageTracker._setDomainName("none");
pageTracker._trackPageview();

Here's some more info on the setDomainName call on Google's site:
_setDomainName API doc

Friday, July 10, 2009 12:25:11 PM (Mountain Standard Time, UTC-07:00)
Hi Mike,
Did you tried to track any genuine share point behind the company intranet and firewall settings ??
If yes then can you guide me what steps exactly you had taken in order to get real stats ? If possible you can make screen shots and publish here on this blog(You can hide or erase any sensitive information).
In my case google is giving following error,upon checking the status of my code.

i checked status of my code in google apps by clicking (Tracking Not Installed ( Check Status [?] )) but it shows following message ..
(Last checked: Jul 9, 2009 9:19:35 AM )
The Google Analytics tracking code has not been detected on your website's home page. For Analytics to function, you or your web administrator must add the code to each page of your website.

Arkesh
Arkesh
Friday, July 10, 2009 6:27:32 PM (Mountain Standard Time, UTC-07:00)
Arkesh,
You are not the first to encounter this conundrum. I've added a post for you to explain how I've fixed this on both a Team Site and Publishing Site:

Enable Google Analytics Page Tracking in a Single-Name Intranet Site
Tuesday, July 14, 2009 12:51:00 PM (Mountain Standard Time, UTC-07:00)
Hi Mike,

Thanks for your help.Now i am getting the sharepoint stats on google analytics.Today it started giving the stats,so i am not sure how is the quality of actual stats ? Please let me know should i have to put GA script to some different master pages also ? if yes then please let me know .

Arkesh
Tuesday, July 14, 2009 7:11:43 PM (Mountain Standard Time, UTC-07:00)
Arkesh,
Glad to hear you got it working. You will need to add the GA script to all master pages which are loaded for pages that require the collection of analytics data. SharePoint Designer is the quickest and easiest tool to use to accomplish this. I would not add the script to application.master however, as application pages tend to be used by administrators and site owners only.
Wednesday, July 15, 2009 10:27:48 AM (Mountain Standard Time, UTC-07:00)
Hi Mike,
According to you one should put google analytics code in following master pages except application.master ???

C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\FEATURES\PublishingLayouts\MasterPages\BlackSingleLevel.master
C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\FEATURES\PublishingLayouts\MasterPages\BlackVertical.master
C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\FEATURES\PublishingLayouts\MasterPages\BlueBand.master
C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\FEATURES\PublishingLayouts\MasterPages\BlueGlassBand.master
C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\FEATURES\PublishingLayouts\MasterPages\BlueTabs.master
C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\FEATURES\PublishingLayouts\MasterPages\BlueVertical.master
C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\FEATURES\PublishingLayouts\MasterPages\OrangeSingleLevel.master
C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\FEATURES\PublishingLayouts\MasterPages\BlackBand.master
C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS\sharepointdevelopment\sharepointdevelopment.master
C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\FEATURES\PublishingResources\PublishingMasterTemplate.master
C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS\application.master
C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS\dialog.master
C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS\layouts.master
C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS\pickerdialog.master
C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS\simple.master
C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS\sspadmin.master
C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\GLOBAL\default.master
C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\GLOBAL\mwsdefault.master
C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\ADMIN\admin.master
C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\ADMIN\popup.master
Arkesh
Monday, July 20, 2009 5:17:35 PM (Mountain Standard Time, UTC-07:00)
I would keep it simple and just modify the minimum master pages required for the pages seen by users, and I would not modify any of the application master pages displayed for Site Settings and other pages in the _layouts folder.

In a publishing site, you can find which master page to modify by going to Site Settings > Master Page (or http://YOUR_SITE/_Layouts/ChangeSiteMasterPage.aspx). There you will see the first master page titled Site Master Page.

In a Team Site, when the site is created there is only one master page created called default.master.

In either type of site, once you have identified which master page(s) to modify, then open the page in SharePoint Designer and add your script.

There are other means to update the page of course depending on one's environment and whether or not solutions and/or SharePoint Designer are in use and who is allowed to edit master pages.
Tuesday, September 01, 2009 8:34:50 AM (Mountain Standard Time, UTC-07:00)
Hello Mike:

Thank you for the great article. I added the required code to the site master of our site. When I view the source I am not seeing the Google code. However, when I login and view source on the same page I see the code. Any Idea?

Thank you,

Kirk
Tuesday, September 01, 2009 8:35:47 AM (Mountain Standard Time, UTC-07:00)
Hello Mike:

Thank you for the great article. I added the required code to the site master of our site. When I view the source I am not seeing the Google code. However, when I login and view source on the same page I see the code. Any Idea?

Thank you,

Kirk
Tuesday, September 01, 2009 8:54:14 PM (Mountain Standard Time, UTC-07:00)
Thanks Kirk. When you view the page prior to logging in and you don't see the Google code - what do you see on that page? Is it a login page or is it the same page as what you see after logging in? If the page you are seeing before-hand is different, then it is using a different master page perhaps?
Wednesday, September 02, 2009 6:54:05 AM (Mountain Standard Time, UTC-07:00)
Thanks for the reply Mike. I am actually on the home page and click on sign in at the top. Before I sign in, i clicked on view source to check for the google code and do not see it. When I click on sign in it takes me to a sign in page and then it takes the user to the MySite. When I return to the home page, with expanded content since I logged in, I click on view source and the google code appears. Is there a location to verify what master page is assigned to a page?
Wednesday, September 02, 2009 7:00:28 AM (Mountain Standard Time, UTC-07:00)
Mike - I forgot to mention, If I drop a content editor webpart on the page, I can see the code. This is what I have done temporarily on the home page.
Wednesday, September 02, 2009 5:11:58 PM (Mountain Standard Time, UTC-07:00)
Kirk, you can see what master page is in use by checking the Page Settings. However if it's a sign-in page, I am curious if maybe it's an ISA Server or similar proxy server that handles the sign-on form? If you can post the path to the page and the page name that might help me have a clue (don't worry about posting the domain). Another way of looking at it is, how necessary is it to even track the sign-on page in Google Analytics? You will know if people made it past sign-on as you would have stats for all the pages they hit after they logged in. Just a thought.


Thursday, January 07, 2010 7:38:28 AM (Mountain Standard Time, UTC-07:00)
Hi Mike.
Great information.
Do you know how to get the outgoing links GA tracking code to work on an Internet Sharepoint site? Referring to: http://www.google.com/support/googleanalytics/bin/answer.py?hl=en&answer=55527
Each time I try to add the code in the link tag while in HTML view it is removed after clicking on Ok. Is there something else that needs to be done to make this work?

We are using the latest version of the tracking code.
Thanks for any help!
Thursday, January 07, 2010 6:41:17 PM (Mountain Standard Time, UTC-07:00)
Jennifer,
I am guessing you are trying to add the code in the link tag in an html editor field control, and then SharePoint is removing the JavaScript when you submit the content update. Try adding the JavaScript into an Html Editor WebPart - SharePoint will not strip the JavaScript out of your web part.
Wednesday, January 13, 2010 6:17:24 PM (Mountain Standard Time, UTC-07:00)
I put it in a content editor webpart and it kept the code there. Thanks so much!

Leave a Comment

Name (required)
Email (will not be published)
Website
 
  Comment (Some html is allowed: a@href@title@target, b, blockquote@cite, em, i, img@src, strike, strong, sub, sup, u) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.
Comment Preview
Subscribe
Top 5 Posts
Add Google Analytics to a SharePoint Publishing Site
Integrating jQuery 1.3, ASP.NET 3.5 Visual Studio 2008
Add Custom Table Formats to SharePoint Content Editor
Configuring log4net for SharePoint Windows Authentication
Convert Visual Studio 2008 Class Library Project to Web Application Project
Tags
ASP.NET (4) dasBlog (5) GoogleAnalytics (2) jQuery (1) log4net (2) SharePoint (18) WebDesign (2)
 
 
 
Spreadfirefox Affiliate Button
 
Install FireBug
 
Download Notepad++