Tuesday, September 1, 2015

Enable tracking of user ids in Google analytics scripts used in Sharepoint

Tracking of user ids in Google Analytics scripts gives you the following benefits (see Benefits of using the User ID feature):

  • Get a more accurate user count
  • Analyze the signed-in user experience
  • Access special tools and reports in your Analytics account
  • Find relationships between your acquisitions, engagement, and conversions

In order to enable it in Sharepoint we need to provide user id of the currently logged in user. On the client side we may get user id of the current user using _spPageContextInfo.userId propery. However _spPageContextInfo object may not be available yet when GA script is executed (see How to get URL of current site collection and other server side properties on client site in Sharepoint about details of internal implementation of this object). In this case we may use delayed script execution in Sharepoint. If regular GA script looks like this;

   1: (function (i, s, o, g, r, a, m) {
   2:     i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {
   3:         (i[r].q = i[r].q || []).push(arguments)
   4:     }, i[r].l = 1 * new Date(); a = s.createElement(o),
   5:     m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)
   6: })(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');
   7:  
   8: ga('create', 'UA-xxxxxx-x', 'auto');
   9: ga('send', 'pageview');

Then script with enabled tracking of user ids for Sharepoint will look like this:

   1: (function (i, s, o, g, r, a, m) {
   2:     i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {
   3:         (i[r].q = i[r].q || []).push(arguments)
   4:     }, i[r].l = 1 * new Date(); a = s.createElement(o),
   5:     m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)
   6: })(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');
   7:  
   8: ExecuteOrDelayUntilScriptLoaded(function () {
   9:     ga('create', 'UA-xxxxxx-x', { 'userId': _spPageContextInfo.userId.toString() });
  10:     ga('send', 'pageview');
  11: }, "sp.js");

Note that we used ExecuteOrDelayUntilScriptLoaded function in order to ensure that _spPageContextInfo is loaded.

2 comments:

  1. hi did you used any custom dimensions or google tag manager?. Please let me know .Thanks
    Rooba

    ReplyDelete