jquerysharepointsharepoint-onlinesharepoint-jsom

SP.ClientContext is undefined in SharePoint online


I am trying to get details of logged In user through JSOM in SharePoint online.

Below is the code which I am trying:

SP.SOD.registerSod('sp.js', "/_layouts/15/sp.js");
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', getCurrentUser);

function getCurrentUser() {
    try {
        var clientContext = new SP.ClientContext.get_current();
        var tempcurrentUser = clientContext.get_web().get_currentUser();
        clientContext.load(tempcurrentUser);
        clientContext.executeQueryAsync(function () {
            prf.loggedUser = tempcurrentUser.get_id();
            var userAcc = tempcurrentUser.get_loginName();                
        }, queryFailure);
    }
    catch (err) {
        queryFailure();
    }
}

function queryFailure() {
    alert('Error while accessing Active Directory');
}

In above code when I am trying to access SP.ClientContext.get_current(), I am getting error stating SP.ClientContext is undefined.

I am new to SharePoint online, this question may be sound easy but I am open to learn.

Note: Above code is working fine in SharePoint 2013.


Solution

  • To get user information in SharePoint online, there is no need to write code. You can use existing _spPageContextInfo provided by Microsoft.

    Code with output:

    enter image description here