Tuesday, January 31, 2012

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


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.

view sourceprint?

*** 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.



view sourceprint?
*** jQUERY METHOD ***
var userName = $().SPServices.SPGetCurrentUser({
fieldName: "Title",
debug: false
});
This option is best and will provide less room for error and more information.

No comments:

Post a Comment