Ram Prasad
 

Getting the URL of SharePoint Pages and Documents using PnPjs in SPFx webparts

Jun, 17 2020
 
1 min/s
 
 

While developing some SPFx webparts or extensions, we might need to find the full URLs of the SharePoint items we read. For example, if we are developing a custom Image Gallery, the SPFx webpart should read all the items from a Image library and also need the full URLs of the images. Similarly when we are showing the list if pages or documents, we might need the full URLs for the pages and documents.

FileRef and EncodedAbsUrl

SharePoint provides 2 internal fields which we can use to find the direct URL for a given resource (page, document, image etc.,)

The FileRef, provides a relative url of the resource, while EncodedAbsUrl provides the full absolute URL for the resource.

Below are the code snippets to read the URLs for pages, documents and images using the PnPjs in your SPFx solutions

import { sp } from "@pnp/sp";
import '@pnp/sp/webs';
import '@pnp/sp/items';
.
.
.
// Pages
const pages = await sp.web.lists.getByTitle("Site Pages").items.select("Title, FileRef, EncodedAbsUrl").get()
console.dir(pages);
.
.
//Documents
const docs = await sp.web.lists.getByTitle("Documents").items.select("Title, FileRef, EncodedAbsUrl").get()
console.dir(docs);

//Images const images = await sp.web.lists.getByTitle("Site Assets").items.select("Title, FileRef, EncodedAbsUrl").get() console.dir(images);

Here is the sample JSON response from these queries.