Get Web URL Based On Page URL Using PnP JavaScript Library


PnP-JS-Core library contains the number of extensible methods and properties. By using it, we can achieve the various actions in a simple code. To know more about this library component, visit the below links,
SharePoint has several building blocks in the collections, which are used to form a SharePoint site. These are used to manage the contents and generate reports based on the contents and settings, etc.
In this post, we will use the PnP-JS-Core utility method to get the Web URL, based on the page URL. For example, we have a page URL, but we want only the Web URL (part of the URL) by trimming the full page URL.
Syntax ( <Absolute path of website> )
Trim the absolute URL of the page and return the web URL.
<Absolute path of website>
Represents the absolute path of a Website under the current Site Collection
The steps and code snippet given below, are used to return the Web URL, based on the provided page URL in a Site Collection.
  1. Download the required files to use PnP-JS-Core library from the links, go and upload it to the Site Assets 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 the Content Editor Web part.
  3. Create a sample.html file in the Site Assets or Style library and insert the code snippet, given below:
    1. <!-- Required JS file -->  
    2. <script type="text/javascript" src="/siteassets/scripts/fetch.js"></script>  
    3. <script type="text/javascript" src="/siteassets/scripts/promise.min.js"></script>  
    4. <script type="text/javascript" src="/siteassets/scripts/pnp.min.js"></script>  
    5. <div id="sample"></div>  
    6. <script type="text/javascript">  
    7. //The below PnP method ' getWebUrlFromPageUrl' used to return the web url  
    8. //Parameter should be absolute url of a website.   
    9. //Here _spPageContextInfo.webAbsoluteUrl returns the absolute url of a current website.  
    10. var pageURL = _spPageContextInfo.webAbsoluteUrl + "/sitepages/testpnp.aspx";  
    11. $ {  
    13. document.getElementById("sample").innerText = data;  
    14. }).catch(function(err) {  
    15. alert(err);  
    16. });  
    17. </script>  
  4. Add the URL of sample.html file to the Content Editor Web Part.
  5. Click OK to apply the changes to the Web part and save the page.
  6. Now, the page displays the Web UR.L


PnP-JS-Core library has several simple extension properties and the methods that help to increase the performance and reduce the number of lines for the code.