Introduction
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
pnp.sp.site.getWebUrlFromPageUrl ( <Absolute path of website> )
Trim the absolute URL of page and return the web URL.
<Absolute path of website>
Represents the absolute path of a Website under the current Site Collection
Example
The steps and code snippet given below, are used to return the Web URL, based on the provided page URL in a Site Collection.
- 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).
- Create new Web part page and insert Content Editor Web part.
- Create a sample.html file in the Site Assets or Style library and insert the code snippet, given below:
-
- <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>
- <div id="sample"></div>
- <script type="text/javascript">
- //The below PnP method ' getWebUrlFromPageUrl' used to return the web url
- //Parameter should be absolute url of a website.
- //Here _spPageContextInfo.webAbsoluteUrl returns the absolute url of a current website.
- var pageURL = _spPageContextInfo.webAbsoluteUrl + "/sitepages/testpnp.aspx";
- $pnp.sp.site.getWebUrlFromPageUrl(pageURL).then(function(data) {
-
- document.getElementById("sample").innerText = data;
- }).catch(function(err) {
- alert(err);
- });
- </script>
- Add the URL of sample.html file to the Content Editor Web Part.
- Click OK to apply the changes to the Web part and save the page.
- Now, the page displays the Web UR.L
Conclusion
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.