How to access the page details in sharepoint custom webparts?

Problem Statement

How to capture the Page Details like Page Title, Page Url for the current page in Sharepoint?

Approach

You can use the PageContext Provided by Sharepoint to get the page ID and you have to get all the pages information from the below method:

How to Get Page ID

let pageId = this.context.pageContext.legacyPageContext["pageItemId"];

Service to Get the Page Details

public async getPageDetails(){

    let web = new Web(this.absoluteurl + "/../DemoCenter");
    let pages = await  web.lists.getByTitle("Site Pages").items.select("Title,GUID,ID,FileRef, EncodedAbsUrl").getAll();
  
return pages;
 }

Method to get the page details and match the details

let pageRes = await this.demoService.getPageDetails();
    if(pageRes)
    pageRes.forEach(async (item) => {
      if (item.Id == pageId && item.ID == pageId) {
        console.log('page id match', item);
        title = item.Title;
        siteUrl = "https://sagportal.sharepoint.com" + item.FileRef;
      }

    });

From this, you will be able to fetch the Page Title and Page Url.

Thank You.

1 Like