SharePoint 2013 UserId using JavaScript

How do you get the userid using JavaScript in SharePoint 2013?

I am using/testing your FREE Piwik self-hosted application for SharePoint 2013.
I applied the JavaScript as instructed to my masterpage as instructed and I am getting data.
However, I am unable to acquire the User information (userid).

I’ve tried using “_spPageContextInfo.userId”, but on the masterpage I need to wait for the “sp.js” to load first.

I’ve tried this:

<script type="text/javascript">
  var _paq = _paq || [];

ExecuteOrDelayUntilScriptLoaded(getPageContextInfo, "sp.js");
function getPageContextInfo() {
    var userId = _spPageContextInfo.userId;
    _paq.push(['setUserId', userId]);
}

  _paq.push(['setDocumentTitle', document.title]);
  _paq.push(['trackPageView']);
  _paq.push(['enableLinkTracking']);
  (function() {
				var u="//localhost/piwik/";
    _paq.push(['setTrackerUrl', u+'piwik.php']);
    _paq.push(['setSiteId', '1']);
    var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
    g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s);
  })();
  
 </script>
<!-- End Piwik Code -->

Any help is appreciated.


Ryan

Hi,

I have no experience with SharePoint, so I could be completely wrong, but I noticed something about your code.

According to the docs You must then pass this User ID string to Piwik via the setUserId method call just before calling track* function, for example:

At the moment you at first track the pageview, then wait for the page to load and then set the userid.

So I think you need to move at least the trackPageView into the asynchronous function.

  var _paq = _paq || [];

ExecuteOrDelayUntilScriptLoaded(getPageContextInfo, "sp.js");
function getPageContextInfo() {
    var userId = _spPageContextInfo.userId;
    _paq.push(['setUserId', userId]); 
    _paq.push(['setDocumentTitle', document.title]);
    _paq.push(['trackPageView']);
}
  _paq.push(['enableLinkTracking']);
  (function() {
				var u="//localhost/piwik/";
    _paq.push(['setTrackerUrl', u+'piwik.php']);
    _paq.push(['setSiteId', '1']);
    var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
    g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s);
  })();
  
 </script>
<!-- End Piwik Code -->

@Lukas - Thanks! I tried this but it didn’t work.

If I add alert(userId) I can see my userId, but it’s not passing to the Piwik > Users.

In retrospect however, the userId is kind of useless. It would be beneficial to get:

  • User Name
  • User Email
  • User Account Name
  • and/or Link to SharePoint Profile

Any help would be appreciated. I am the sole SharePoint Developer at my organization and have been tasked to get Piwik installed.

Cheers!

Hi,

If you want to store more data, Custom Dimentions are ideal.

About your issue: I can’t help that much, but if you check the network tab of your browser, you can see the request to piwik.php which is sending the data. That way you can find out if the issue is in the tracking code or if Piwik isn’t working correctly.

Piwik is working correctly.

If I put single quotes around userid as seen below I get userid in the the Visitors > Users.

_paq.push(['setUserId', 'userId']); // string value userId appears in Visitors > Users

If I add alert(userid) I see my userid pop up.

However, I believe that because I am waiting for the sp.js file to load the delay prevents Piwik from setting the userid in Visitors > Users.

I will keep trying to figure this out, but I would assume this is a common situation.

Solved!

See my script below.
It works for me using SharePoint 2013

I borrowed the script from the REST API at the bottom of this page:

<!-- Piwik -->
	    <script type="text/javascript">
	    var _paq = _paq || [];
		
            ExecuteOrDelayUntilScriptLoaded(getPageContextInfo, "core.js");
				
	    function getPageContextInfo() {
		
            /* START GET USER NAME */
            var userid = _spPageContextInfo.userId; // GET USERID
            var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";
            var requestHeaders = { "accept": "application/json;odata=verbose" };
	    $.ajax({
	        url: requestUri,
	        contentType: "application/json;odata=verbose",
	        headers: requestHeaders,
	        success: onSuccess,
	        error: onError
	    });

	    function onSuccess(data, request) { // SUCCESS
                var Logg = data.d;
	        var HRMIS = Logg.LoginName.split('|')[1]; // ACCOUNT LOGGED IN
	        var displayName = Logg.Title; // DISPLAY NAME
	        HRMIS = HRMIS.replace('ross\\', '' ); // REMOVE ROSS
	        piwikUser = displayName+' ('+HRMIS+')'; // SET PIWIK USER
	        piwikUser = piwikUser.toString();
	        _paq.push(['setUserId', piwikUser]);
	    }
	
	    function onError(error) { // ERROR
	        _paq.push(['setUserId', 'error']); // RECORD USER AS ERROR
	    } 
		/* END GET USER NAME */
		
		// accurately measure the time spent on the last pageview of a visit
        _paq.push(['enableHeartBeatTimer']);
        
		_paq.push(['setDocumentTitle', document.title]);
		_paq.push(['trackPageView']);
		_paq.push(['enableLinkTracking']);
		}
		
		(function() {
			var u="//localhost/piwik/";
			_paq.push(['setTrackerUrl', u+'piwik.php']);
			_paq.push(['setSiteId', '1']);
			var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
			g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s);
		})();
		</script>
		<!-- End Piwik Code -->