Get Web URL from a Page URL in SharePoint Site Collection

This post explains, how to get the web url from page url in SharePoint Site Collection using PnP JavaScript Library.

In this article, we will cover how to use the PnP JS Core library to get the web url from any page url with in the SharePoint Site Collection. To know more about this JavaScript library, check the below links

In this post,

How to get web url from page url using PnP JavaScript Library.

Syntax:

pnp.sp.site.getWebUrlFromPageUrl(absolutePageUrl) - 
Returns the website URL based on the absolute Page URL passed as parameter

Example:

The below steps and code snippets used to get a web url from the page url in SharePoint Site Collection using PnP JavaScript library,

  1. Download Required files to use PnP-JS-Core library from the below links and upload that to Site Asstes or Style Library
    • Download pnp.js  PnP JS file
    • Download fetch.js Used by PnP js file to handle web requests and responses (Required in IE)
    • Download promise.js Used by PnP js file to handle web requests and responses (Required in IE)
  2. Create new web part page and insert Content Editor web part
  3. Create a sample.html file in Site Assets or Style library and insert the below code snippet

[code language=”js”]

<script type="text/javascript" src="/siteassets/scripts/fetch.js"></script>
<script type="text/javascript" src="/siteassets/scripts/promise.min.js"></script>
<script type="text/javascript" src="/siteassets/scripts/pnp.min.js"></script>

Web URL: <span id="sample"></span>

<script type="text/javascript">
//The below PnP method from SiteCollection object returns the web url from page url
$pnp.sp.site.getWebUrlFromPageUrl(‘https://ktskumar.sharepoint.com/sites/team/SitePages/Home.aspx’)
.then(function(res) {
document.getElementById(‘sample’).innerHTML = res;
});
</script>

[/code]

Typescript Example:

Typescript is the superset of JavaScript and this PnP JS library is developed using the typescript specification. For developing the SharePoint Framework web parts and make the client side development easier, we can vote for typescript. The below is the typescript example for retrieving the web url from any page url in  Site Collection.

[code language=”js”]

import pnp from "sp-pnp-js";

pnp.sp.site.getWebUrlFromPageUrl(‘https://ktskumar.sharepoint.com/sites/team/SitePages/Home.aspx’)
.then(res => {
document.getElementById(‘sample’).innerHTML = res;
});

[/code]

Output:

Web URL: https://ktskumar.sharepoint.com/sites/team
Shantha Kumar
Shantha Kumar
Articles: 280