The Ultimate Guide to Setting Up Google Analytics in SharePoint

Here's everything you need to know to install Google Analytics on your SharePoint intranet. But are you sure you want to?

The Ultimate Guide to Setting Up Google Analytics in SharePoint

📜 This guide was originally published by my co-founder Bradley Geldenhuys on February 11, 2019. It was moved from the SharePoint Vitals standalone blog to the Vinewave Blog in April 2021. The steps contained in this post may no longer work exactly as indicated, but the concepts should be the same.


Before we begin...

The CONS 👎 of using Google Analytics in SharePoint

So you've come all this way on the internet to find out how to install Google Analytics (GA) in SharePoint, and the first thing we tell you is NOT to use Google Analytics in your SharePoint environment?

What gives?

Well, here's 6 reasons:

  1. Google strictly prohibits the capturing of Person Identifiable Information (PII) which you accept when signing up for Google Analytics. This means that even if you figure out a way to track the account names from your SharePoint environment, you are in violation of Google's Analytics terms of service and they can remove your data at any time and ban you from the service. This means that understanding user trends and pulling specific reports on departments is not possible.

    "...prohibits sending personally identifiable information (PII) to Analytics (such as names, social security numbers, email addresses, or any similar data), or data that permanently identifies a particular device (such as a mobile phone’s unique device identifier if such an identifier cannot be reset)."
  2. The service is only free for up to 10 million hits per month and then you'll be charged.
  3. Data privacy. Once you hand over your SharePoint intranet URLs to Google Analytics, there's a possibility they could be included in Google's organic search results too. Your SharePoint intranet page URLs probably contain some very sensitive information.
  4. Document usage analytics is not available in Google Analytics as it does not track documents or files, only pages. Documents are a huge part of SharePoint so you'll probably want to have analytics around this.
  5. Site-specific group permissions are not available in Google Analytics, so everyone who has access to your Google Analytics account has access to all the analytics data for your entire intranet.
  6. Google Analytics wasn't designed for SharePoint and intranets. It was built to be used on public facing websites to allow website owners to analyze the browsing habits of their visitors. Your intranet on the other hand is more than just a browsing experience; it's a collaboration experience that goes way deeper than just a few dozen/hundred pages.

With that out the way, if you still want to add Google Analytics to your SharePoint intranet, here's how you do it.

Step 1 - Figure out your SharePoint version

There are several versions of SharePoint, but we can break them up into two categories.

On-premises, which consists of SharePoint 2007, 2010, 2013, 2016 and 2019, and SharePoint Online, which is part of Office 365.

In order to deploy Google Analytics to a SharePoint site, you'll first need to know which version of SharePoint you are deploying to.

Getting your Google Analytics tracking code for SharePoint

In order to gather analytics from your SharePoint environment, you'll need to sign up to Google Analytics (GA) and identify your SharePoint site with a tracking code.

  1. Go to https://analytics.google.com and sign up or sign in.

2. Click on the Admin cog on the dashboard (bottom left).

3. Under the Admin Tab, find ‘Account’ and click ‘+ Create Account’.

Create an account in Google Analytics

4. Fill in the required fields and uncheck all the boxes, unless you really do want to share your corporate information with Google 👀

Account Name, Website Name, Website URL, Industry Category, Reporting Time Zone
New account in Google Analytics

5. Click Get Tracking ID.

6. You will be prompted to accept the Google Analytics Terms of Service Agreement based on your region.

Google Analytics Terms of Service

Some notes from the terms:

Subject to Section 15, the Service is provided without charge to You for up to 10 million Hits per month per account. Any outstanding balance becomes immediately due and payable upon termination of this Agreement and any collection expenses (including legal fees) incurred by Google will be included in the amount owed, and may be charged to the credit card or other billing mechanism associated with Your AdWords account.

You will not and will not assist or permit any third party to, pass information to Google that Google could use or recognize as personally identifiable information. You will have and abide by an appropriate Privacy Policy and will comply with all applicable laws, policies, and regulations relating to the collection of information from Visitors. You must post a Privacy Policy and that Privacy Policy must provide notice of Your use of cookies that are used to collect data. You must disclose the use of Google Analytics, and how it collects and processes data.

To the extent permitted by applicable law, You will indemnify, hold harmless and defend Google and its wholly owned subsidiaries, at Your expense, from any and all third-party claims, actions, proceedings and suits brought against Google or any of its officers, directors, employees, agents or affiliates, and all related liabilities, damages, settlements, penalties, fines, costs or expenses (including, reasonable lawyers’ fees and other litigation expenses) incurred by Google or any of its officers, directors, employees, agents or affiliates, arising out of or relating to (i) Your breach of any term or condition of this Agreement, (ii) Your use of the Service, (iii) Your violations of applicable laws, rules or regulations in connection with the Service, (iv) any representations and warranties made by You concerning any aspect of the Service, the Software or Reports to any Third Party; (v) any claims made by or on behalf of any Third Party pertaining directly or indirectly to Your use of the Service, the Software or Reports; (vi) violations of Your obligations of privacy to any Third Party; and (vii) any claims with respect to acts or omissions of any Third Party in connection with the Service, the Software or Reports.

If You use the Service on behalf of the Third Party or a Third Party otherwise uses the Service through Your Account, whether or not You are authorized by Google to do so, then You represent and warrant that (a) You are authorised to act on behalf of, and bind to this Agreement, the Third Party to all obligations that You have under this Agreement, (b) Google may share with the Third Party any Customer Data that is specific to the Third Party’s Properties, and (c) You will not disclose Third Party’s Customer Data to any other party without the Third Party’s consent.

If you agree to the full Google Analytics Terms of Service Agreement, click ‘I accept’ to continue.

7. Copy your tracking code for the next step: Deploying to SharePoint.

How to deploy Google Analytics into SharePoint

To deploy your Google Analytics (GA) to SharePoint, you will need to find out what version of SharePoint you are running.

This is pretty straightforward, just follow this guide 👉 Which version of SharePoint am I using

💡 If you're still unsure, check out the HTTP response header for MicrosoftSharePointTeamServices and compare it to this guide. To do this, browse to your SharePoint site, bring up the development console (by pressing F12) and search for ‘MicrosoftSharePointTeamServices’.

The following versions numbers are related to the version of SharePoint available.

12.0+ (SharePoint 2007)
14.0+ (SharePoint 2010)
15.0+ (SharePoint 2013)
16.0.4+ (SharePoint 2016)
16.0.1 - 16.0.2 (SharePoint 2019)
16.0.0.8+ (SharePoint Online

Installing Google Analytics on SharePoint 2010/2013

For SharePoint 2010 and 2013 you'll either need a WSP or a Farm Solution, and you'll need to be a SharePoint Site Collection Admin or a SharePoint Farm Administrator.

* You can also use this method to create solutions for 2016/2019 but leveraging the SharePoint Framework is preferred (see below).

1. Fire up Visual Studio and create a SharePoint 2013 - Empty project called "GoogleAnalyticsforSharePoint" or "ILoveBlueCheese" 🧀

SharePoint Solution

2. Lets select a farm solution as they are easy to deploy and manage if you're are a farm administrator.

SharePoint security level

3. Wait for Visual Studio to create the project...

4. Once the project has been created, choose Add >New Item.

5. Select Empty Element and name it CustomAction.

6. Add another New Item and this time select Module, and call it Style Library.

💡 Once created, feel free to delete ‘Sample.txt’ from the Style Library Module.

7. Create a folder structure: Style Library/GA/js

8. Add a new JavaScript file to the /GA/js folder. Name the file ga.js 👇

9. This is what your final file structure should look like:

10. Update the SharePoint Feature information to have a proper Title and Description.

11. Add the following code to your ga.js file and make sure to set the ‘Tracking ID’ to the tracking ID given to you from the Google Analytics site.

(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),

m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)

})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

ga('create', 'Tracking ID', 'auto');

ga('send', 'pageview');

12. Now run the application and test:

13. In SharePoint, under Site Settings > Site Features, you will notice our feature:

14. Check your real-time analytics in Google Analytics, and if you're lucky, you'll see some activity.

Installing Google Analytics on SharePoint Online

For SharePoint Online, or SharePoint 2016/2019, you'll need to create the application customizer extension project that's provided by the SharePoint Framework.

In SharePoint Online, you're no longer able to add code via a WSP or a sandboxed solution.

⚠️ We strongly encourage you not to inject this code into the master page or via a JavaScript web part.

The below guide shows a SharePoint Online deployment of Google Analytics, but this can be used in the same way for adding Google Analytics to SharePoint 2016 or SharePoint 2019.

1. Run the following from a command prompt (CMD):

Yo @microsoft/sharepoint

2. Once successfully deployed you should see this:

3. Open the project in Visual Studio by selecting Open > Folder … > {Location of the saved project above in step 1}.

4. Locate the following file:

/src/extensions/gaForSharePoint/GaForSharePointApplicationCustomizer.ts

5. Find the export interface and change the sample code and comment from this...

...to this...

6. In the same GaForSharePointApplicationCustomizer.ts file, locate

/** A Custom Action which can be run during execution of a Client Side Application */

export default class GaForSharePointApplicationCustomizer

extends BaseApplicationCustomizer {private currentPage = "";


  private isInitialLoad = true;

  private getFreshCurrentPage(): string {

    return window.location.pathname + window.location.search;

  }

  private updateCurrentPage(): void {

    this.currentPage = this.getFreshCurrentPage();

  }

  private navigatedEvent(): void {

    let trackingID: string = this.properties.trackingID;

    if (!trackingID) {

      Log.info(LOG_SOURCE, `${strings.MissingID}`);

    } else {

      const navigatedPage = this.getFreshCurrentPage();

      if (this.isInitialLoad) {

        this.realInitialNavigatedEvent(trackingID);

        this.updateCurrentPage();

        this.isInitialLoad = false;

      }

      else if (!this.isInitialLoad && (navigatedPage !== this.currentPage)) {

        this.realNavigatedEvent(trackingID);

        this.updateCurrentPage();

      }

    }

  }

  private realInitialNavigatedEvent(trackingID: string): void {

    console.log("Tracking full page load...");

    var gtagScript = document.createElement("script");

    gtagScript.type = "text/javascript";

    gtagScript.src = `https://www.googletagmanager.com/gtag/js?id=${trackingID}`;

    gtagScript.async = true;

    document.head.appendChild(gtagScript);

    eval(`

        window.dataLayer = window.dataLayer || [];

        function gtag(){dataLayer.push(arguments);}

        gtag('js', new Date());

        gtag('config',  '${trackingID}');

      `);

  }

  private realNavigatedEvent(trackingID: string): void {

    console.log("Tracking partial page load...");

    eval(`

      if(ga) {

        ga('create', '${trackingID}', 'auto');

        ga('set', 'page', '${this.getFreshCurrentPage()}');

        ga('send', 'pageview');

      }

      `);

  }

  @override

  public onInit(): Promise {

    this.context.application.navigatedEvent.add(this, this.navigatedEvent);

    return Promise.resolve();

  }

7. Run a command prompt in the "Google Analytics for SharePoint" package folder and run the following command:

gulp bundle –ship

8. Now build the solution with the following command:

gulp package-solution –ship

9. You'll be able to find the package in the \sharepoint\solution sub-folder with the file extension *.sppkg

📝 Extensions won’t be automatically enabled. SharePoint Framework extensions must be specifically associated to sites, lists, and fields programmatically to be visible to site users.


Ok, now that you've got your SPFx package (sppkg) you'll need to deploy the solution to SharePoint.

To achieve the steps described in the following section you'll first need to install SharePoint PnP PowerShell. To do this, open PowerShell as admin and run the following command:

Install-Module SharePointPnPPowerShellOnline

(You'll need this later.)


10. Log onto SharePoint Office 365 as Admin, then go to SharePoint Admin.

11. Select Apps > App Catalog.

12. In the App Catalog, select ‘Distribute apps for SharePoint’

13. Click ‘New’ and select the package location from step 7. Check the "Make this solution available to all sites in the organization" box and click Deploy.

14. You're in the final stretch 🏁 Now you simply need to connect to Office 365 and enable the extension with the PowerShell commands you installed earlier.

Run the following command to connect to your Office 365 tenant, making sure to change the URL to your own:

Connect-PnPOnline -UseWebLogin -Url https://changeme.sharepoint.com

15. Now, enable the extensions by running the following command, remembering to change the UA Tracking ID to the one you received from Google when creating the Analytics Account, along with the ID Guid from your project found in manifest.json.

Add-PnPCustomAction -ClientSideComponentId "id guid" -Name "Google Analytics for SharePoint" -Title "GA for SharePoint" -Location ClientSideExtension.ApplicationCustomizer -ClientSideComponentProperties: '{"trackingID":"UA-change-me"}' -Scope site

💡 If you receive Access Denied errors, make sure you're logged in with a user account that has Owner rights on the SharePoint site you're deploying to.

16. Verify that your code is working by heading over to Google Analytics.

17. Pour yourself a drink, you earned it 🥂

18. Subscribe for our future posts 😉

References

http://sharepoint.handsontek.net/2017/02/26/how-to-add-google-analytics-to-sharepoint-without-modifying-the-master-page/

http://sharepoint.handsontek.net/2017/12/21/how-to-add-google-analytics-to-the-modern-sharepoint/

https://www.c-sharpcorner.com/article/add-google-analytics-to-sharepoint-sites/

https://code.msdn.microsoft.com/office/Implementing-Google-cb2cc027

https://docs.microsoft.com/en-us/sharepoint/dev/spfx/extensions/get-started/using-page-placeholder-with-extensions

https://stackoverflow.com/questions/48882321/google-analytics-and-sharepoint-online

https://sharepoint.stackexchange.com/questions/210372/how-do-i-add-google-analytics-into-sharepoint-2013-on-line

https://www.youtube.com/watch?v=K9SpAVdo7I8

http://www.sharepointdiary.com/2014/05/how-to-integrate-google-analytics-with-sharepoint.html

https://www.tatvasoft.com.au/blog/event-tracking-in-google-analytics-with-sharepoint-online/

https://support.shortpoint.com/support/solutions/articles/1000265440-how-to-track-your-sharepoint-site-usage-with-google-analytics

https://fiechter.eu/2014/02/24/google-analytics-for-sharepoint-2013-office-365/

https://social.technet.microsoft.com/Forums/en-US/1e0b548a-3235-4b13-bf80-ffef2e681991/applying-google-analytics-code-on-sharepoint-online-sites-o365?forum=CloudSSA

https://blog.mastykarz.nl/tracking-links-google-analytics-sharepoint-2010-mavention-google-analytics-links-tracking/

https://gist.github.com/vgrem/2884bdad94d450e0f869

https://www.anupams.net/azure-application-insights-google-analytics-sharepoint/

https://blog.intlock.com/analyzing-visitor-paths-using-google-analytics/

https://zimmergren.net/integrating-the-google-analytics-api-in-sharepoint-in-order-to-enable-users-to-review-analytics-data-directly/

https://allcloud.com/blog/optimizing-google-analytics-for-sharepoint-and-office-365/