SharePoint 2010 Get Current Username / Logged in User

Have been exploring the SharePoint Client Object Model and in particular the Javascript Object Model

While there are methods to get the current user info, you can also simply borrow the logged in username from the top right of the screen:


<script type="text/javascript">// <![CDATA[
 var Username = document.getElementById("zz16_Menu").innerHTML ;
 var end = Username.indexOf("<");
 var nameOnly = Username.substring(8, end);
 document.write(nameOnly);

// ]]></script>

This technique is a little complex for my liking however, so here’s a snappier way to grab the current login name (using Jquery):


var Username = $("#zz16_Menu").text();
document.write(Username);

Note that the #zz16 identifier will vary based on your Master page. Use the Firefox Web Developer tools or Internet Explorer F12 tools to find out what the ID should be on your SharePoint site.

Using this type of technique is definitely more brittle than actually using a CAML query however in my mind would be more performant than actually doing a lookup in the DB. Would love to know if someone knows the scoop on that..

Update 05/12/2011

As my colleague Colin pointed out – the name that appears on the top right can really be anything and can change – for example if a user gets married and their name changes. A better approach would be to retireve the value programmatically using SPServices ( http://spservices.codeplex.com/wikipage?title=$%28%29.SPServices.SPGetCurrentUser ). As of version v0.6.1, you can also request the ID of the user by specifying fieldName: “ID”.  Much more stable to use in most scenarios:

$().SPServices.SPGetCurrentUser({
	fieldName: "ID",
	debug: false
});

Incoming search terms:

Tags: , , , ,

Trackback from your site.

Keith Tuomi

Keith is SharePoint Consultant and problem solver with itgroove. He's been focused on Microsoft technologies as a Developer and Web Applications specialist since the beginning of the internet era in the early '90s, with formal training coming from the esteemed British Columbia Institute of Technology. He is a SharePoint MVP, which is a coveted Microsoft award for community contributions and technical excellence. Keith has wide array of international experience and is also adapt at translating your business needs into bits & bytes.

Leave a comment

Follow me on Twitter