How to Get current loggedin user in Sharepoint using Javascript

This a script that gets the current logged-in user’s name from the welcome menu and populates it in a People Picker control.

Firstly, to run the function on page sharepoint load user spBodyOnLoadFunctionNames something like below.

_spBodyOnLoadFunctionNames.push(“AddCurrentUserToPP”);

Next add this script in any content editor webpart or just on your custom page.

function AddCurrentUserToPP()
{
var currentUser = GetUser();
if(currentUser != null)
{
var pp = GetPeoplePickerText(document.getElementById(‘PeoplePickerId’).parentNode);

//set the People picker field to current user
if(pp != null)
pp.innerText = currentUser;
}
}

function GetUser()
{
var tags = document.getElementsByTagName(‘a’);
for (var i=0; i < tags.length; i++)
{
if(tags[i].innerText.substr(0,7) == ‘Welcome’)
{
return tags[i].innerText.substr(8,tags[i].innerText.length);
}
}

}

function GetPeoplePickerText(container)
{
var result = “”;

var _divs = container.getElementsByTagName(“DIV”);
for(var k=0; k < divs.length; k++)
{
if(divs[k].id.indexOf(identifier) > 0 && divs[k].id.indexOf(“UserField_upLevelDiv”) > 0)
{
result = divs[k];
break;
// You can also access the text in the control by using the below
var innerSpans = divs[k].getElementsByTagName(“SPAN”);
for(var j=0; j < innerSpans.length; j++)
{ if(innerSpans[j].id == ‘content’)
{ return innerSpans[j].innerHTML;}
}

}
return result;
}