Wednesday, September 15, 2010

How to get currently logged in User through JavaScript In SharePoint?

Since JavaScript is very useful tool for processing code on Client Side, It saves lot of response time and becomes very efficient Following code extract is very useful in finding out currently logged In user in SharePoint programmatically.


If you are running the Client Object Model (ClientOM) from javascript, then you should load the "sp.js" file using the ScriptLink.RegisterOnDemand method (a static method). In a web part, I recommend calling this in your OnPreRender override.



<SharePoint:ScriptLink ID="get_spUser" runat="server" Name="sp.js" Localizable="false" LoadAfterUI="true" />



The script code that will call into the ClientOM must not run until the "sp.js" file is loaded. SharePoint provides a method to help with this and this method is part of init.js, meaning that you need not register any further script files from SharePoint. To run a method named Initialize, use the following call:


ExecuteOrDelayUntilScriptLoaded( getCurrentUser, "sp.js");


Here's is the code for getting curreent logged In user in javascript-



<script type="text/javascript">

ExecuteOrDelayUntilScriptLoaded( getCurrentUser, "sp.js");

var context = null;

var web = null;

var currentUser = null;



function getCurrentUser() {

context = new SP.ClientContext.get_current();

web = context.get_web();

currentUser = web.get_currentUser();

currentUser.retrieve();

context.load(web);

context.executeQueryAsync(Function.createDelegate(this, this.onSuccessMethod), Function.createDelegate(this, this.onFailureMethod));

}


function onSuccessMethod(sender, args) {

var userObject = web.get_currentUser();

alert('User name:' + userObject.get_title() + '\n Login Name:' + userObject.get_loginName());

}



function onFaiureMethodl(sender, args) {

alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());

}


</script>




The above code returns you the user object and displays user name and user login name. You can customize it as you want.

2 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Hi Pravin, i was not able to make this script run on my WSS 3.0, since i'm a newbie on this i thought taht maybe since i wasn't writing the _spBodyOnLoadFunctionNames.push the script wasn't running, but i believe this was solved with the ExecuteOrDelayUntilScriptLoaded( getCurrentUser, "sp.js"); right? so what do you think could be the problem?

    ReplyDelete