The Ultimate Guide to Setup Google Analytics for SharePoint.

There are several versions of SharePoint, but we can break them up into two categories. On-premises, which consist of SharePoint 2007,2010,2013,2016 and 2019, and then SharePoint Online, which is part of Office 365.

In order to deploy Google Analytics to a SharePoint site, you will need to know which type of SharePoint you are deploying to first.

How to setup Google Analytics

In order to gather analytics, you will need to signup to Google Analytics (GA) and identify your SharePoint site with a tracking code.

  1. Go to and signup or sign in.
  2. On the dashboard find the Admin cog at the bottom left and click it.
  3. Under the Admin Tab, find ‘Account’ and click ‘+ Create Account’.
  4. Fill in the following information required 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

And then click Get Tracking ID.

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


  • 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 above and the other parts not shown here in the agreement click ‘I accept’ to continue.  If you do not agree, click ‘I Do Not Accept’ and find an alternative solution.

  1. Copy your tracking code for the next step, deploying to SharePoint

How to deploy Google Analytics

To deploy your Google Analytics (GA) to SharePoint, you will need to find out what version of SharePoint you are in fact running.  This is pretty straight forward follow this guide “Which version of SharePoint am I using” and if you still unsure check out the HTTP Response header for MicrosoftSharePointTeamServices and compare it to this guide.

Browse to your SharePoint site, push F12 in the browser to bring up the development console and search for ‘MicrosoftSharePointTeamServices’.

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


SharePoint 2007


SharePoint 2010


SharePoint 2013


SharePoint 2016


SharePoint 2019

SharePoint Online


SharePoint 2010/2013

For SharePoint 2010 and 2013 you either need a WSP or Farm Solution and depending on who you are in the business a Site Collection Admin or a Farm Administrator you would require either or, let me show you both.

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

  1. Fire up Visual Studio and find SharePoint 2013– Empty Project

I am going to create a SharePoint 2013 Empty project and call it ‘GoogleAnalyticsforSharePoint’.

Lets select a farm solution as they are easy to deploy and manage as long as you are a farm administrator.

Once the project has been created add a New Item.

Select Empty Element and call it Custom Action

And 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.

Now create a folder structure within Style Library GA->js

Then add a Javascript File to GA>JS file structure

This is what your final file structure should look like

Now update the Feature information to have a proper Title and Description

Now add the following code to your ga.js file and ensure to change ‘Tracking ID’ with the actually tracking ID given to you from the Google Analytics site.

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



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

  ga('send', 'pageview');

Now simply Run the application and test.

Under Site Settings > Site Features, you will notice our feature.

Check your Real-time analytics on the Google


For SharePoint Online/2016/2019, you will need to create the application customizer extension project which is provided by the SharePoint Framework.  You are no longer allowed to add code via WSP or sandboxed solutions and I strongly encourage you not to inject this code into the master page or JavaScript web part.  It just becomes more difficult to manage and does not capture all visitors which skews the numbers and therefore pointless.

The below guide shows an Online deployment but can be used in the very same way for 2016/2019 deployments.

  1. Run the following from CMD

Yo @microsoft/sharepoint

Once successfully deployed you should see this.

  1. Open the project in Visual Studio by selecting Open > Folder … > Location of the saved project above in step 1.
  2. Locate src/extensions/gaForSharePoint/GaForSharePointApplicationCustomizer.ts.
  3. Find the export interface and remove the sample code and notes from this

To this

export interface IGaForSharePointApplicationCustomizerProperties {

  // Google Analytics Tracking ID

  trackingID: string;


  1. In the same file ‘GaForSharePointApplicationCustomizer.ts locate

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

extends BaseApplicationCustomizer {private currentPage = "";

replace all the code below with the following.

  private isInitialLoad = true;

  private getFreshCurrentPage(): string {

    return window.location.pathname +;


  private updateCurrentPage(): void {

    this.currentPage = this.getFreshCurrentPage();


  private navigatedEvent(): void {

    let trackingID: string =;

    if (!trackingID) {, `${strings.MissingID}`);

    } else {

      const navigatedPage = this.getFreshCurrentPage();

      if (this.isInitialLoad) {



        this.isInitialLoad = false;


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






  private realInitialNavigatedEvent(trackingID: string): void {

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

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

    gtagScript.type = "text/javascript";

    gtagScript.src = `${trackingID}`;

    gtagScript.async = true;



        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...");


      if(ga) {

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

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

        ga('send', 'pageview');





  public onInit(): Promise {

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

    return Promise.resolve();

  1. Then from CMD prompt in the Google Analytics for SharePoint package folder run the following command

gulp bundle –ship

  1. Now build the solution with the following command;
gulp package-solution –ship

You will be able to find the package under sharepoint\solution with the file extension *.sppkg

  1. 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.

To achieve the steps described in this section you will need to install the SharePoint PnP PowerShell.

In PowerShell as admin simply run the following command;

Install-Module SharePointPnPPowerShellOnline

We will need this later.

  1. Log onto SharePoint Office 365 as Admin > Go to SharePoint Admin.

Select Apps > App Catalog.

In App Catalog select ‘Distribute apps for SharePoint’.

Click ‘New’ and select the package location from step 7.

Make sure the solution is available to all sites in the organization and click ‘Deploy’.

  1. Now we are at the final stretch, we simply need to connect to Office 365 and enable the extension with the PowerShell commands we installed earlier.

Run the following command to connect to your Office 365 tenant, changing the URL to your own.

Connect-PnPOnline -UseWebLogin -Url
  1. Now we 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 do receive any errors about Access denied, make sure the user you have logged in with has Owner rights on the site you are deploying too.

  1. Check to ensure your code is working head over to the Google Analytics.

Cons of using Google Analytics

  1. Google strictly prohibit the capturing of Person Identifiable Information (PPI) which you accept when signing up for GA. This means that even if you figure out a way to add the account names to monitoring you are in violation of their policy and they can remove your data at any time and ban you from using the service.

This then means that understanding user trends pulling specific reports on teams and management is not possible.

  1. The service is only free up to 10 million hit per month and then billing will occur via Adwords account.
  2. Data Security – I personally think some of the URL’s found are used in the search engine crawlers, if you simply google your private URL after adding google analytics to it, you may find the URL there with multiple sub sites leaking directory structure. The only way this is possible is if the site map is being created by analytics and shared with Google crawlers.
  3. Document usage analytics is not available in GA as it does not track document usage or file downloads, only page hits.
  4. Site specific group permissions are not available in GA, so everyone who has access to GA has access to the results.
  5. GA was not designed for SharePoint and intranets, it was designed for public facing sites to allow website owners to better their sites, generate more traffic and there for sell more ads for Google.

If you are serious about SharePoint specific analytics and how to improve your intranet and user adoption get a tool that was developed and designed with exactly that in mind SharePoint Vitals

References – – 

2 thoughts on “The Ultimate Guide to Setup Google Analytics for SharePoint.”

  1. Hello,

    I was wondering if it is normal that the function realNavigatedEvent is never called?

    I was wondering how it could be called since the script is called only when the page is initially loaded.

    I’d like to run the script when a user open a folder in SharePoint Online Modern experience.

    Am I doing something wrong?


  2. Hi,

    I followed the same and trying to activate it on SharePoint 2019 On-Premise, the app deployed successfully, but when I apply pnpCustomAction, I get following error:

    Add-PnPCustomAction : Field or property “HostProperties” does not exist.
    At line:1 char:1
    + Add-PnPCustomAction -ClientSideComponentId “73e…..”

Leave a Reply

Your email address will not be published. Required fields are marked *