How To Get Current Context From SharePoint Modern Site Page

Today we will see how to get the current context information from Modern Pages. In Classical Pages and anything other than modern site pages, we can get the current web and user context information using the _spPageContextInfo variable.
 
But when we try to access the same variable in modern site pages, we will get an undefined error. If we change the page to view source mode, we will see this _spPageContextInfo JavaScript variable is commented. Due to that we won’t access the current context information.
 
There is a workaround available and that too has come from SharePoint. We must use the full Modern Page URL to send the request along with “as=json” as a query string.
 
Format of the Request URL,
  • http://domaoin.sharepoint.com/sites/name/sitepages/modernpage.aspx
  • http://domaoin.sharepoint.com/sites/name – If the modern page is the home page of the site
To test this, navigate to the modern site page. Then open the browser console and paste the below code snippet,
  1. //Reference URL https://gist.github.com/ktskumar/ab378261b9f7d349254043dc935c08d9#file-getmodernpagecontext-js   
  2.   
  3. //getRequest method reference  - https://gist.github.com/ktskumar/a9e9df497673e9fd26ead8532b9ff425   
  4. function getRequest(url) {    
  5.     var request = new XMLHttpRequest();    
  6.     return new Promise(function(resolve, reject) {    
  7.         request.onreadystatechange = function() {    
  8.             if (request.readyState !== 4) return;    
  9.             if (request.status >= 200 && request.status < 300) {    
  10.                 resolve(request);    
  11.             } else {    
  12.                 reject({    
  13.                     status: request.status,    
  14.                     statusText: request.statusText    
  15.                 });    
  16.             }    
  17.         };    
  18.     
  19.         request.open('GET', url, true);    
  20.         request.setRequestHeader("Content-Type""application/json;charset=utf-8");    
  21.         request.setRequestHeader("ACCEPT""application/json; odata.metadata=minimal");    
  22.         request.setRequestHeader("ODATA-VERSION""4.0");    
  23.         request.send();    
  24.     
  25.     });    
  26. }    
  27.     
  28. //Get the Request location from the browser URL    
  29. var path = location.href.replace(location.search, "") + "?as=json";    
  30.     
  31. //Returns the current user, item, page and context information    
  32. getRequest(path).then(function(response) {    
  33.     console.log(JSON.parse(response.response));    
  34. });    
And it returns the context information of current user, current page properties, current item properties and current web properties.