PnP-JS-Core: Get available web parts from Site Collection

PnP-JS-Core library contains the number of extensible methods and properties. By using that we can achieve the various actions in a simple code. To know more about this library component, visit the below links,

Simplified JavaScript Library for SharePoint

PnP-JS-Core Library

In this post, we will see

How to get the available web parts from SharePoint “Web Part Gallery” using PnP-JS-Core library.

Example:

The below steps and code snippet used to get the webpart’s name from web part gallery in a 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 
      //To get individual property of an SharePoint object use select(<propertyname>) before get() method
      
      $pnp.sp.web.lists.getByTitle("Web Part Gallery").items.select('FileLeafRef').get().then(function(result) {
      var webParts = "Total available Web Parts: " + result.length+"<br/>";
      for (var i = 0; i &lt; result.length; i++) {
      webParts += result[i].FileLeafRef + "<br/>";
      }
      document.getElementById("sample").innerHTML = webParts;
      //console.log(webParts);
      });
       
       
      
      
    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 each web part’s name available in Web part Gallery .

Leave a Reply

Your email address will not be published. Required fields are marked *