2

I want to add something along the lines of "Welcome, [user]" to the top of my homepage. I'd like it be as simple as possible (no SharePoint designer or customization to the master page). Just a simple CSS or javascript code (I still don't know the difference :) ) that I can add to a script editor or content editor web part. I found some codes that would include the user's picture and email, but I don't know code well enough to edit that part out. Please help!

1 Answer 1

1

You can use this javascript SharePoint javascript object model to get the current logged in user. Put this code in a content editor web part on the homepage.

<div id="displayName"></div> 

<script type="text/javascript">
var clientContext = new SP.ClientContext(_spPageContextInfo.webServerRelativeUrl);
var user = clientContext.get_web().get_currentUser();
clientContext.load(user);

clientContext.executeQueryAsync(onUserNameSuccess, onUserNameFail);
function onUserNameSuccess() {
    document.getElementById("displayName").innerText = "Welcome, " + user.get_title();
    //To display last name first and for cases where full name consists of only two words.
    //var userToken = user.get_title().split(' ');
    //document.getElementById("displayName").innerText = "Welcome, " + userToken[1] + " " + userToken[0];

}

function onUserNameFail(args) {
    document.getElementById("displayName").innerText = 'Error:' + args.get_message();
}
//recommended to use ExecuteOrDelayUntilScriptLoaded on sp.js
</script>
2
  • Thanks, this worked! Is there anyway to flip the name so it's First then Last, not last then first? That's just me being picky :)
    – user69859
    Commented Sep 6, 2017 at 16:55
  • @user69859 I have updated the answer with the code sample. You can extend the sample for more than 2 words in full name. The user full name is most likely set as "last, first" in your active directory or SharePoint user profile.
    – Ahmad Zia
    Commented Sep 7, 2017 at 2:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.