How to add Google Analytics to SharePoint without modifying the master page

Google Analytics is the most widely used web analytics service in the internet, it provides a concise analysis with reports of everything that happens in your site as well as real time reports, mostly targeted for public sites it also works on intranets.

Intranet portals are the central hub of companies; important information is communicated to employees through these portals and you need to make sure that everyone can access to it no matter the device or technologies used.

Analyzing your intranet portal will help you to understand how users interact with it, what are the most viewed sites and what sites do you need to improve.

Add JavaScript File

With this being said let’s check how you can add google analytics tracking to your SharePoint site without touching the master page.

In this article, I explain step by step how to build and deploy a script link using a custom action into SharePoint, I am also providing the installation files and the instructions to use it if you don’t want to build it yourself.

How to setup Google Analytics

First things first, before we get into the SharePoint bits let’s set up google analytics and get everything you need.

  1. Sign in to your Analytics account
  2. Select the Admin tab
  3. Select an account from the menu in the ACCOUNT column, or CREATE NEW ACCOUNT if you don’t have one already
  4. Select a property from the menu in the PROPERTY column
  5. Under PROPERTY, click Tracking Info Tracking Code
  6. Save the Website tracking script code
    Save Google Analytics tracking code

More information about google analytics setup can be found here.

Create SriptLink Custom Action

If you are not into code jump to the next section.

  1. Open Visual Studio and create a new project
  2. Select Office/SharePoint templates and SharePoint Empty Project
  3. I’ll call it SharePointGoogleAnalytics, but you can call it whatever you want
    New SharePoint project
  4. Provide the URL for the site to use to debug
  5. Select Deploy as sandboxed solution and click Finish
    SharePoint Customisation Wizard
  6. Once your project opens go to the Properties and set Include Assembly in Package to False, this is required to build a declarative sandbox solution
    SharePoint Solution Properties
  7. Right click on your project, go to Add and select New Item
  8. Select Empty Element and call it AnalyticsCA, this will be the ScriptLink Custom Action
    Add new item
  9. Right click on your project, go to Add and select New Item
  10. Select Module and call it Style Library
  11. Delete the Sample.txt file that is created by default
  12. Create the folder structure below inside the Style Library Module
    GoogleAnalytics js
  13. Right click in the js folder, go to Add and select New Item, from the Web group select the JavaScript File and call it ga.js
    SharePoint Project Structure
  14. At this point your project structure should look like the image below
    SharePoint Feature Properties
  15. Open the Elements.xml file inside the Style Library module, this file is generated by Visual Studio automatically however I like to modify it to it to publish the files automatically once the solution is activated and to replace the files if a previous version already exists in the system. Select the entire content of the file and replace it by the code below.
  16. Open the Elements.xml inside the AnalyticsCA module and paste the code below.

    This xml file will register the custom action and will execute the ga.js in all sites of your site collection.

  18. Open the Features folder and rename the Feature1 to GoogleAnalytics feature
  19. Open GoogleAnalytics feature
  20. Type a Title and Description for your features, both fields will be visible in your site collection
  21. Change the scope from Web to Site, this way the script will be deployed to all the sites in the site collection
    Add JavaScript File
  22. Open the ga.js file in the Style Library module and paste there the script code you got from Google without the script tags. Your code will be like the code below except for the Track ID
      (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
      ga('create', 'Track ID', 'auto');
      ga('send', 'pageview');
  23. Compile your project and deploy the solution to all the site collection you want to track

Once you deploy the solution your Google Analytics dashboard will immediately display real time data.

Add JavaScript File

Install Google Analytics on SharePoint

To install the solution in your SharePoint and start tracking your sites follow this steps:

  1. Download the solution
  2. On your site collection root site go to Settings Site Settings Solutions
  3. Upload and activate the solution, once you activate the solution google analytics script is immediately added to your site however it is not tracking your site yet, you still need to add your track id to the script
  4. Open your site with SharePoint designer
  5. Go to All Files Style Library Google Analytics js
  6. Check out and edit the ga.js file in advanced mode
  7. Locate the words TRACK ID and replace it by your own track id from Google Analytics
    Add JavaScript File
  8. Save the file check it in and publish it as major version.

You are good to go; your site collection is being tracked by google analytics.

If you have multiple site collections and don’t want to open SharePoint designer for every single one to edit the JavaScript file you can use my SharePoint WSP Repackage tool to modify the solution and create your own unique WSP with your Track ID.

How deactivate Google Analytics tracking

If you want to stop tracking a specific site collection do the following:

  1. On your site collection root site and go to Settings Site Settings Site Collection Features
  2. Locate the Google Analytics feature and deactivate it
    Add JavaScript File


In this article, you learned how to add Google Analytics to SharePoint without touching the master pages and how to create a script link custom action step by step.

If the master page was blocking the analytics adoption in your company either because you are on SharePoint Online or because you don’t want to break your beautiful custom master page this is the way to go.

Unfortunately, this solution will not work on the new Team Sites and Document Libraries on SharePoint Online because for now they are no script sites. As soon as something comes out to support those sites I’ll review this article.

A new version of this article for Modern SharePoint is available here.

As always the source code of this project is available on my personal GitHub repository and you can download the WSP solution from this article, the links are down below.

Download Google Analytics WSP
Explore Solution on GitHub

Designed by Freepik

51 Responses to “How to add Google Analytics to SharePoint without modifying the master page”

  1. Tobias Roth

    September 26, 2017

    Hey Joao,
    thank you for the Article. Great News for me who’s working with GA and who has several potential clients where I can implement this!

    Since it is a JavaScript that was set up, you will not have any problems with implementing other (tracking-) codes right? If I’m not mistaken you will also be able to put in your Google Tag Manager!? Would be great!

    Greetings from Germany

    • João Ferreira

      October 11, 2017

      Hi Tobias,

      Since this is just script you can implement what ever you want.
      You have access to the script file, it’s located in the style library.

  2. Gaurav Goyal

    October 22, 2017


  3. João Ferreira

    November 12, 2017

    Hi Alexander,

    Unless you have a script error this solution will run in all your sites with the exception of the modern office 365.
    Make sure that the feature is active in the site collection where the blog is.

  4. Dean Whittaker

    November 22, 2017

    Hi Joao,

    I set this up on a site we use at work using the 2nd method, it seems to be working fine but the page views only show the home page and not any of the new blogs etc.. Have I done something wrong in the setup?



    • João Ferreira

      November 22, 2017

      Hi Dean,

      Can you please check in the browser console if there is any script error?
      The analytics script is added to all the sites and pages with the exception of modern site in the site collection.
      I’ll inspect this further to check if there is something that I can do in the code specifically for blogs.

  5. João Ferreira

    December 18, 2017

    Hi Anderson,

    Are you using the WSP provided by me or have you built the solution yourself?
    Please make sure that the tracking code on the ga.js script was replaced, and the file is published and checked in.
    To debug the ga.js script do the following using google chrome.

    1. On the site where you have the google analytics press F12
    2. Press CTRL + P and then type ga.js
    3. Open the ga.js file and verify if the line ga('create', 'UA-XXXXXX-1', 'auto'); has your unique tracking code

    Let me know how it went.
    Please notice that this solution is only valid to the classic SharePoint it will not work for the modern pages, I’m working on a solution for the modern pages and it should be available here in the blog before Christmas.

    • Sudeep

      April 17, 2018


      I had similar problem, when I checked using inspect element I found out that the TRACKING ID was not updated. What could be the possible solution?

      • João Ferreira

        April 17, 2018


        Some users reported that the file was not properly checked in with SharePoint designer, try to check in and publish the file with the browser. After it refresh your browser using CTRL + F5 to make sure the browser chache is cleaned and the file loads the latest version.

  6. Kgakgamatso

    February 26, 2018

    thanks for sharing. However i am experiencing errors with the solution:

    I tried the first one with downloading Google analytics but not able to activate, it just stays greyed out.
    (Too bad i cant upload screen shot in here)

    The second solution of Visual gives me the following error:

    Severity Code Description Project File Line Suppression State
    Error Error occurred in deployment step ‘Activate Features’: Failed to instantiate file “ga.js” from module “StyleLibraryJS”: Source path “Features\SharePointGoogleAnalytics_GoogleAnalytics feature\Style Library\GoogleAnalytics\js\ga.js” not found. SharePointGoogleAnalytics 0

    • João Ferreira

      March 4, 2018


      Usually when the solution stays grayed out means that the file uploaded was not the wsp but the zip file, can you please confirm if the solution is uploaded is the wsp?

  7. Wagner

    April 9, 2018

    Oi Joao, muito obrigado pelo post!
    Tenho um problema, so aparece um usuario online no analytics (EU), mas sei que tem muitos outros online no momento e ja fiz o teste com um amigo do trabalho tambem, mas nao aparece que ninguem esta no site a nao ser eu. Este e um site em SharePoint Online, usamos o “classic view” e nossos usuarios tem que autenticar para accessar o site. O que voce acha sobre isso? O que voce recomenda fazer para eu poder usar o Google Analytics?

    Muito obrigado!


    • João Ferreira

      April 15, 2018

      Olá Wagner,

      Nunca tive esse problema as unicas vezes em que dei conta que o utilizador não aparece no analytics é quando estou no memsmo browser com sessão aberta no analytics.
      Voce já testou em outra rede para tentar perceber se é alguma limitação de rede que causa o problema?

      • Wagner

        April 16, 2018

        Ola Joao,

        O problema foi porque estava usando o SharePoint Designer para editar o JavaScript direto do site. E check-in, check-out e Publish nao funcionam bem no SPD. Depois de fazer as edicoes correteas fui no browser e publish o js file. Agora vejo todos meus usiarios online.
        Tenho uma outra pergunta, qual o User Profile property que posso usar no js file para mostrar o nome ou email de meus usuarios? Estou usando o codigo abaixo:

        ExecuteOrDelayUntilScriptLoaded(function (){
        ga(‘create’, ‘MyTrackID’, ‘auto’, { ‘userId’: _spPageContextInfo.userId.toString() });
        ga(‘send’, ‘pageview’);
        }, “sp.js”);

        Muito obrigado desde ja Joao!

        • João Ferreira

          April 16, 2018

          Olá Wagner,

          Obrigado pelo seu feedback, fico contente que tenha conseguido colocar a solução a funcionar.
          Para guardar o nome ou email do utilizador deve fazer os seguintes passos:

          1 – No analytics criar uma custom dimension
          2 – Guardar o index da dimension ex. dimension1
          3 – Editar o ficheiro ga.js com o SharePoint designer
          4 – Substituir o código ga pelo código abaixo, substituindo o index da dimension

          ExecuteOrDelayUntilScriptLoaded(getPageContextInfo, "core.js");
          function getPageContextInfo() {
          	ga('create', 'UA-92611503-1', 'auto');
          	ga('send', 'pageview',{
          	  'dimension1':  _spPageContextInfo.userLoginName

          5 – A propriedade userLoginName só existe no SharePoint Online, para SharePoint on prem pode usar o userId
          6 – No analytics criar um custom report
          7 – Seleccionar a custom dimension na opção Dimension Drilldowns

          8 – Guardar e abrir o novo report, os utilizadores vão aparecer como na imagem abaixo

          Wagner, sei que há vários passos envolvidos se achar confuso diga e eu preparo um artigo mais detalhado.

        • João Ferreira

          April 18, 2018

          Olá Wagner,

          Aqui está um novo artigo com isntruções passo a passo de como enviar o email do utilizador.

  8. Tracy

    May 1, 2018

    Hi and thank you for the information. Does this solution work with Office 365 SharePoint Online?
    I’m having some trouble getting the install to work , and wondering if this will implement on my system.


    • João Ferreira

      May 1, 2018

      Hi Tracy,

      Yes this solution works for Office 365 SharePoint Online.
      Were you able to install the package in the site collection?

      My best,

      João Ferreira

  9. Yuriy

    May 14, 2018

    I have installed the solution and it seems to work for me.
    But during our testing on the first day from 3 different countries we missed out one user/region.
    There was even moment when I was shown like current online user from Amsterdam, but I can not see The Netherlands in the countries list for this day?
    Do you think it is some GA error/settings or errors at out sharepoint site/browsers etc?

    • João Ferreira

      May 14, 2018

      Hi Yuriy,

      If this is a SharePoint error it must be a script error. Open the browser console on the missing one and check if you have script errors. If everything is ok in your console it might be related with ga.

  10. Payal Varshney

    June 12, 2018

    Hi Joao,

    Its really helpful article for beginners. Can you provide any post regrading the implementation of Google Tag Manager in SharePoint Website. If yes, then it will be very helpful.
    Thanks in advance.

    From India

    • João Ferreira

      June 15, 2018

      Hi Payal,

      I can do it, it doesn’t seem to be much different than this one.

      • Divya

        June 3, 2019

        Hi Joao,
        Thank you very much for the article. It fails to work with Google Tag Manger in SharePoint 2013 on-prem.
        Could you pls provide any post or advice to make it work.

        Thanks, Divya

        • João Ferreira

          June 10, 2019

          Hi Divya,

          I’ll debug the solution on my side to inspect what might be the issue.
          In the meantime can you please press F12 and let me know if you have any script error in your browser console?

          • Divya

            June 10, 2019

            Hi Joao,
            I just created a new sandbox solution and deployed it. It works like a charm in SP2013 on-prem. Thank you very much for this article!!

          • João Ferreira

            June 10, 2019

            Thanks for your feedback

  11. Poppy

    July 4, 2018

    Any ideas how to get Google Tag Manager to work in the same way (ie without altering the master page)?
    We’ve tried everything – and also trying to tag individual elements. No success… 🙁

    • João Ferreira

      July 31, 2018

      Hi Poppy,

      Google tag manager will need it’s own custom solution, I’ll try to get you a solution in one of my upcoming posts.

      • Poppy

        August 1, 2018

        Great! Thanks.

        • Ihsan

          October 2, 2018

          is there any update on this one as it i was expecting something to happen in in past few months.

          • João Ferreira

            October 10, 2018

            The update to the analytics solution is not yet available, but I should release new versions this month.

  12. Martin Brendan

    August 7, 2018

    I am glad to find it. There are so many developers working on this part but this is one of the best innovative post ever. Thanks for such post.

  13. zack

    October 9, 2018

    Have Visual Studio Version 15.7.5.
    I am trying to implement this of sharepoint online site.
    When i goto > VS > New Project > Sharepoint Empt Project > Sharepoint is not installed error

    • João Ferreira

      October 10, 2018

      Hi Zack,

      To create the project you will need to do it in a server with SharePoint installed, otherwise the option will not appear.

  14. Minoarijaona RAMAHENINA

    October 9, 2018


    I implemented your second solution on a SharePoint Online site and it worked fine. But now I don’t seem to receive anymore data.
    I changed the ID in te ga.js script and I published it and I don’t know where the issue can come from.

    Do you have any idea? 🙂

    Thank you for your answers

    • João Ferreira

      October 10, 2018


      Sometimes when you are with the google analytics and SharePoint sessions open in the same browser the information will not reach Google Analytics.
      Please try to access to the site in a different browser.
      A couple other things that you can check to make sure there are no issues with the solution:
      1 – Open the browser console and check if you have any script error, if you do it might be the cause of the issue, in case of error let me know what the error is
      2 – Make sure the analytics number is correct in the JS file
      3 – Make sure the modified file was checked in and published as a major version

  15. Joaquim Costa

    January 30, 2019

    Olá João,

    Já coloquei a funcionar, no entanto a recolha de informação não é feita nos site collections. Terei que fazer um ID para cada site collections?

    • Joaquim Costa

      January 30, 2019

      Já confirmei, é preciso instalar em todos os site collections com o mesmo ID 🙂

      • João Ferreira

        February 3, 2019

        Exactamente Joaquim, é uma das limitações desta solução no SharePoint classico, tem de ser instalada em todas as site collections.

  16. Daniel Westerdale

    February 12, 2019


    Great post. I would like implement a universal approach to GA on both a classic SharePoint portal ( it is has lots cs customisation ) and modern sites ( Comms, Hub Group enabled) . Hence I am guessing for the former, I will need to touch master page – unless you can think of an alternative . In which case , I guess I am looking at injecting a site action or hooking into the current async code.

    Here is an alternative approach we can if you GA isn’t the best approach.

    • João Ferreira

      February 14, 2019

      Hi Daniel,

      You can follow this article to get it applied to classic SharePoint without touching the master page.
      For modern SharePoint you can follow 2 different approaches:
      This article will add GA on modern SharePoint and needs to be defined per site collection (compatible with SharePoint 2019)
      This article applies it globally to all modern sites and pages in the tenant (compatible just with Office 365)

  17. Keauna Ford

    February 20, 2019

    What version of Visual Studio should we use?

    • João Ferreira

      February 20, 2019

      Hello, Visual studio 2013 running on a server with SharePoint installed. The solution is also available as wsp ready to install

      • Keauna Ford

        March 6, 2019

        Do it make a difference if Visual studio is on the front end or app server. Will Visual studio 2017 work?

        • João Ferreira

          March 7, 2019

          Hi Keauna,

          Never tested the Visual Studio on the Front end Server, but I think it will work.
          In order to run this project you will need Visual Studio 2013.

          • Keauna Ford

            March 12, 2019


            I don’t see the Office/Sharepoint under Visual C# once I go to Visual Studio and try to create a new project.

  18. Keauna Ford

    March 20, 2019

    The solution is to download Office Developer Tools for Visual Stuido 2013. You can use the website to download the Office Developer Tools for Visual Stuido 2013.

    Keauna Ford

  19. Levan

    May 22, 2019

    I have downloaded the solution and activated .it was working at the first time then i tried to reactivate the solution i couldn’t able to do that. I’m getting error stating that The solution cannot be deployed. Directory “SharePointGoogleAnalytics_GoogleAnalytics feature” associated with feature ’32e42e8c-7967-4008-981f-6e09e0188d3b’ in the solution is used by feature ‘1f588a18-8e8c-4118-ab49-ae7effc927a0’ installed in the farm. All features must have unique directories to avoid overwriting files.

    • João Ferreira

      June 10, 2019

      Hi Levan,

      This solution is provided as a SandBox solution and needs to deployed on each site collection in the solution gallery.
      Have you deployed the solution to the farm using powershell?


Leave a Reply

I've been working with Microsoft Technologies over the last ten years, mainly focused on creating collaboration and productivity solutions that drive the adoption of Microsoft Modern Workplace.

%d bloggers like this: