SOLVED

_spPageContextInfo is undefined

Iron Contributor

I have a very simple REST call to get all of the items in a list(Announcements) but when I run this Mikael's script editor web part I get this error _spPageContextInfo' is not defined. where _spPageContextInfo is the current url of the page I am in).

 

What am I doing wrong (I am using modern pages) ?

$.ajax({
  url: _spPageContextInfo.webAbsoluteUrl +
    "/_api/web/lists/getbytitle('Announcements')/items",
  method: "GET",
  headers: {
    "Accept": "application/json; odata=verbose"
  },
  success: function(data) {
    console.log(data.d.results);
  },
  error: function(data) {
    alert(JSON.stringify(error));
  }
});

3 Replies
best response confirmed by Nigel Price (Iron Contributor)
Solution

Does it work on a classic page?

 

In this thread (https://github.com/Microsoft/types-publisher/issues/363) it is mentioned that the SharePoint constants (like _spPageContextInfo) are not supported in modern pages. I think that (as useful as it may be) Mikael Svensson's Spfx web part that allows you to host JavaScript on a modern page should probably be thought of as a hack, and wouldn't be considered supported by MS.

 

The supported solution would be to create an Spfx web part for your customization, and use the REST call from within it. Within the Spfx web part you can get the current page's context using "this.context.pageContext" - so you can use 

"this.context.pageContext.web.absoluteUrl" to get the URL of the current web
 
Thanks
 
Nigel

Hi @NigelWitherdin Thanks for explaining why _spPageContextInfo does not wok in modern pages.  I missed that.  I agree with you the way forward is to use the SPFx webpart.  But for a quick Proof of Concept Mikael's webpart is fine.

 

Regards

 

Nigel

We have 3 cloud tenant with 3 different domains. For one cloud tenant _spPageContextInfo is completely blank. Will this be due to improper AD synch

1 best response

Accepted Solutions
best response confirmed by Nigel Price (Iron Contributor)
Solution

Does it work on a classic page?

 

In this thread (https://github.com/Microsoft/types-publisher/issues/363) it is mentioned that the SharePoint constants (like _spPageContextInfo) are not supported in modern pages. I think that (as useful as it may be) Mikael Svensson's Spfx web part that allows you to host JavaScript on a modern page should probably be thought of as a hack, and wouldn't be considered supported by MS.

 

The supported solution would be to create an Spfx web part for your customization, and use the REST call from within it. Within the Spfx web part you can get the current page's context using "this.context.pageContext" - so you can use 

"this.context.pageContext.web.absoluteUrl" to get the URL of the current web
 
Thanks
 
Nigel

View solution in original post