Using jQuery to Find the Current Logged in User SharePoint 2010

JavaScript / jQuery on the page at either:

  • $(document).ready
  • _spBodyOnLoadFunctionNames
will not return the required result, since the menu elements we need to interrogate have not been rendered yet.
Solution:
  • Set a timer to keep running a particular function to wait until the menu is rendered
  • Stop the timer
  • Interrogate the DOM as required using jQuery
 Code Example:
 <script type='text/javascript'>
   var timerHandle =""; 
   var currentWindowsAccount="";
  _spBodyOnLoadFunctionNames.push("runCustom"); 
  function runCustom() {
  timerHandle = setTimeout(getCurrentLoggedInUser, 10;
  } 
  function getCurrentLoggedInUser() { 
  //Function requires jQuery
  /* Retrieve the current logged in user from the My Profile option in **
  ** the Welcome Menu (id=ID_MySiteLinksMenu) ** 
  ** This needs a timeout to wait for the menu to be rendered via AJAX */
  //Timers are expensive on client resources, clear at all opportunities
    clearTimeout(timerHandle);
    var welcomeMenuItems =$('#ID_MySiteLinksMenu'); //ie:menu with id='ID_MySiteLinksMenu'

     if(welcomeMenuItems.length>0) { 
     var onmenuclickValue = welcomeMenuItems.attr("onmenuclick");
     var onmenuclicksplit = onmenuclickValue.split("=");
     var loggedInUserString = onmenuclicksplit[1];
     var loggedInUserStringSplit = loggedInUserString.split("'"); 
     currentWindowsAccount = loggedInUserStringSplit[0]; 
     alert(currentWindowsAccount); 
     } 
     else{ 
    //My Profile link has not been rendered yet, try again.
      timerHandle = setTimeout(getCurrentLoggedInUser, 10); 
     } 
      } 
      </script>

Leave a comment