How to get the logged on users name from a SharePoint page using javascript

Often I have wanted to get the user’s name, or other user properties, when a SharePoint user hits my site. Instead of writing code against the SharePoint object model within a custom web part, there are two additional methods to consider if you are trying to accomplish the same thing. One is to look at the source of the page to find the element that contains this information, or to query the SharePoint web services.

OPTION 1 Using Javascript to find the ‘zz8_Menu’ element in HTML

Choosing this method will only get the users name and won’t make a call to external services to find out who is viewing the page. If you only need the name of the user, i’d recommend this option since there isn’t a need to make an unncessary call to the server.

*** JAVASCRIPT METHOD ***
<script language="javascript">
	var whoami = document.getElementById("zz8_Menu").innerHTML;
	var end = whoami.indexOf("<");
	var nameOnly = whoami.substring(8, end);
	alert(whoami);
</script>

OPTION 2 Using the SPServices jQuery Library

This option will query the SharePoint web services to get user information, including the user id and other properties.


*** jQUERY METHOD ***
var userName = $().SPServices.SPGetCurrentUser({
                    fieldName: "Title",
                    debug: false
                    });

This option is best and will provide less room for error and more information. For additional properties of what you can return from this query, see the SPServices jQuery Library.

.advertisement

Leave a Reply