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 https://analytics.google.com 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.

Notes

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

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

 

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.

(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');

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

Online

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 + 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();

  }
  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 https://changeme.sharepoint.com
  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

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://joelfmrodrigues.wordpress.com/2019/01/10/add-google-analytics-to-sharepoint-modern-pages/ 

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

http://www.allthingssharepoint.nl/add-google-analytics-sharepoint-sharepoint-2013-sharepoint-online-office-365/ 

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/ 

https://sharepoint.uservoice.com/forums/329214-sites-and-collaboration/suggestions/33823753-google-analytics-for-communication-sites 

Leave a Reply

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