How to fetch the current context information from a modern SharePoint page using Script Editor web part

If you want to get information about the current page, the current site, and the current user, and you keep trying to use code you usually use on classic SharePoint but it doesn’t work on modern, then this article is for you!

 

In classic SharePoint pages and anything other than modern site pages, you can get the current web and user context information using the _spPageContextInfo variable.
But if you try to access the same variable in modern site pages, an undefined value appears. If you change the page to view in source mode, you will also see that _spPageContextInfo JavaScript variable is commented. As it stands, you will not be able to access the current context information and well, that is a problem.

 

Fortunately, there is an easy fix.
Follow along to see BindTuning Script Editor web part used in what is a perfect use case:

Fetch current context information from a modern SharePoint page

 

Navigate to a modern site page and add a BindTuning Script Editor web part with the bellow code between a <script> tag.
//getRequest method reference
function getRequest(url) {
    var request = new XMLHttpRequest();
    return new Promise(function(resolve, reject) {
        request.onreadystatechange = function() {
            if (request.readyState !== 4) return;
            if (request.status >= 200 && request.status < 300) {
                resolve(request);
            } else {
                reject({
                    status: request.status,
                    statusText: request.statusText
                });
            }
        };

        request.open('GET', url, true);
        request.setRequestHeader("Content-Type", "application/json;charset=utf-8");
        request.setRequestHeader("ACCEPT", "application/json; odata.metadata=minimal");
        request.setRequestHeader("ODATA-VERSION", "4.0");
        request.send();
    });
}
    
//Get the Request location from the browser URL
var path = location.href.replace(location.search, "") + "?as=json";

//Returns the current user, item, page and context information
getRequest(path).then(function(resp) {
    window["__btCurrentContextInfo"] = JSON.parse(resp.response);
});

An added bonus

Using the Script Editor web part this script will return the current user's context information, current page properties, current item properties, and current web properties as well as add the result to a window variable that can be used whenever desired
Have more questions? Submit a request

Comments

BindTuning logo
Copyright Ⓒ 2021 Bind.
All rights reserved.
Privacy Policy
Cookie Policy
BindTuning
              Linkedin BindTuning Twitter BindTuning YouTube BindTuning Instagram BindTuning
              Facebook
Powered by Zendesk