Get Document Libraries from SharePoint Web using PnP JavaScript Library

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

SharePoint has lot of building blocks in collections which are used to form a SharePoint site. Those are used in manage the contents, generate reports based on contents & settings, etc…

In this post, we will use the PnP-JS-Core method to get the collection of document libraries from based on website URl using the SiteCollection method.

Syntax:

pnp.sp.site.getDocumentLibraries( <Absolute path of website>

Returns the collection of document libraries associated to SharePoint website based on the provided web absolute URL.

Example:

The below steps and code snippet used to returns the root web object and properties from the current site collection.

  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)
  1. Create new web part page and insert Content Editor web part
  2. Create a sample.html file in Site Assets or Style library and insert the below code snippet
    <!-- Required Scripts -->
    <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 'getDocumentLibraries' used to return the document libraries from the site collection
    //Parameter should be absolute url of a website. Here _spPageContextInfo.webAbsoluteUrl returns the absolute url of a current website.
    $pnp.sp.site.getDocumentLibraries(_spPageContextInfo.webAbsoluteUrl).then(function(data) {
     var strTitle = "";
     for (var i = 0; i < data.length; i++) {
     strTitle += data[i].Title + '\r\n';
    
     }
     document.getElementById("sample").innerText = strTitle;
    
    }).catch(function(err) {
     alert(err);
    });
    </script></pre>
    
  3. Add the URL of sample.html file to the content editor web part
  4. Click ok to apply the changes to the web part and save the page.
  5. Now the page displays the title of all visible document libraries from the website.

Leave a Reply

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