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: - 
Returns the website URL based on the absolute Page URL passed as parameter


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

<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
 .then(function(res) {
 document.getElementById('sample').innerHTML = res;

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.

import pnp from "sp-pnp-js";'')
 .then(res => {
 document.getElementById('sample').innerHTML = res;


Web URL: