Question

I am using sp-pnp-js for my spfx project. GetWebUrlFromPageUrl method is returning wrong URL that includes sitePages also. Please refer: my current page location is https://xxxx.sharepoint.com/sites/abc/SitePages/Search.aspx

The above method is returning web url as: https://xxxx.sharepoint.com/sites/abc/SitePages

rather it should return: https://xxxx.sharepoint.com/sites/abc/

pnp.sp.site.getWebUrlFromPageUrl(window.location.href)
 .then(res => {
 alert(res);
});

Please note this issue is not appearing in workbench. This appears only when only when I deployed the code to SharePoint site

What am I missing?

Edit 1: Screen shot- see the current URL is having /SitePages/. But if I run the same from workbench it doesn't throw error

enter image description here

Was it helpful?

Solution

Not really sure why GetWebUrlFromPageUrl is not working. But as you mentioned in the comment that you want the current sp web url, you can use the this.context.pageContext object.

No need to make a REST api call to get the current sp web url.

For example, in the render method, using React, it is available as below:

public render(): void {
const element: React.ReactElement<any > = React.createElement(
   HelloWorld,
   {
     spWebUrl: this.context.pageContext.web.absoluteUrl     
   }
);

 ReactDom.render(element, this.domElement);
}

Or, using it in a simple no-framework solution as below:

let spWebUrl = '';
public render(): void {
    spWebUrl = this.context.pageContext.web.absoluteUrl;
}

After that, you can use the spWebUrl anywhere in your code.

I believe that this will be a much faster and correct way to get the current web url. GetWebUrlFromPageUrl internally made a POST request to the _api/sp.web.getweburlfrompageurl(@v) endpoint and then gave you the data(in your case, incorrect data). However, this.context.pageContext object saves you this API call and provides the correct result.

OTHER TIPS

if it helps someone else I had the same problem and to solve it had to initiate the pnp.setup

 public onInit(): Promise<void> {
    return super.onInit().then(_ => { 
      pnp.setup({
      spfxContext: this.context
      });
      });
  } 
Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top