Articles about European Sharepoint Hosting Service
SharePoint 2013 Hosting – HostForLIFE.eu :: 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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
//Reference URL https://gist.github.com/ktskumar/ab378261b9f7d349254043dc935c08d9#file-getmodernpagecontext-js //getRequest method reference - https://gist.github.com/ktskumar/a9e9df497673e9fd26ead8532b9ff425 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(response) { console.log(JSON.parse(response.response)); }); |
And it returns the context information of current user, current page properties, current item properties and current web properties.
Print article | This entry was posted by Peter on February 27, 2020 at 8:43 am, and is filed under European SharePoint 2013 Hosting. Follow any responses to this post through RSS 2.0. Both comments and pings are currently closed. |