10 Examples of Retrieving the Current Site Collection Context and URL in SharePoint Online using SPFx

SharePoint Framework (SPFx) is a powerful tool for creating client-side web parts and extensions in SharePoint Online. One common requirement when developing SPFx solutions is retrieving the context of the current site collection and its URL. This article provides 10 examples of how to achieve this using SPFx and the REST API to interact with the SharePoint Online environment.

Prerequisites

Before diving into the examples, ensure that you have the following prerequisites:

  • A SharePoint Online tenant
  • A SharePoint Framework (SPFx) development environment set up
  • Node.js and Yeoman SharePoint Generator installed
  • A basic understanding of how SPFx works

Example 1: Retrieve the Site Collection URL Using this.context.pageContext

The easiest way to get the site collection URL is through the this.context.pageContext object available in the SPFx web part. Here’s how you can do it.

public render(): void {
  const siteCollectionUrl: string = this.context.pageContext.site.absoluteUrl;
  console.log("Site Collection URL:", siteCollectionUrl);
}

Example 2: Retrieve the Site Collection URL Using REST API

You can also use the REST API to fetch the URL of the current site collection.

import { sp } from '@pnp/sp';

public async getSiteCollectionUrl(): Promise<void> {
  try {
    const site = await sp.site.get();
    console.log("Site Collection URL:", site.Url);
  } catch (error) {
    console.error("Error retrieving site collection URL:", error);
  }
}

Example 3: Retrieve the Current Site URL Using this.context.pageContext

This example uses this.context.pageContext.web.absoluteUrl to get the URL of the current site.

public render(): void {
  const currentSiteUrl: string = this.context.pageContext.web.absoluteUrl;
  console.log("Current Site URL:", currentSiteUrl);
}

Example 4: Retrieve the Current Site URL Using REST API

In this example, we use the REST API to fetch the URL of the current site.

import { sp } from '@pnp/sp';

public async getCurrentSiteUrl(): Promise<void> {
  try {
    const web = await sp.web.get();
    console.log("Current Site URL:", web.Url);
  } catch (error) {
    console.error("Error retrieving current site URL:", error);
  }
}

Example 5: Get the Site Collection Title Using this.context.pageContext

You can also get the title of the site collection using this.context.pageContext.

public render(): void {
  const siteCollectionTitle: string = this.context.pageContext.site.title;
  console.log("Site Collection Title:", siteCollectionTitle);
}

Example 6: Get the Site Collection Title Using REST API

Using the REST API, you can get the site collection’s title as well.

import { sp } from '@pnp/sp';

public async getSiteCollectionTitle(): Promise<void> {
  try {
    const site = await sp.site.get();
    console.log("Site Collection Title:", site.Title);
  } catch (error) {
    console.error("Error retrieving site collection title:", error);
  }
}

Example 7: Retrieve Current Site Context Using this.context.pageContext

The this.context.pageContext provides more than just the URL. You can also retrieve the context, including the site and web details.

public render(): void {
  const pageContext = this.context.pageContext;
  console.log("Page Context:", pageContext);
}

Example 8: Retrieve Web Context Using REST API

You can fetch the web context with the REST API, including details such as title, URL, and more.

import { sp } from '@pnp/sp';

public async getWebContext(): Promise<void> {
  try {
    const webContext = await sp.web.get();
    console.log("Web Context:", webContext);
  } catch (error) {
    console.error("Error retrieving web context:", error);
  }
}

Example 9: Fetch Site Collection Information Using PnPjs

The PnPjs library makes it easy to retrieve site collection information like the title and URL. Here’s an example of using PnPjs to get the site collection details.

import { sp } from '@pnp/sp';

public async fetchSiteCollectionInfo(): Promise<void> {
  try {
    const siteInfo = await sp.site.get();
    console.log("Site Collection Information:", siteInfo);
  } catch (error) {
    console.error("Error fetching site collection info:", error);
  }
}

Example 10: Create a Simple Web Part to Display the Site URL Using REST API

Finally, let’s create a simple web part that displays the current site collection’s URL using the REST API.

import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';
import { sp } from '@pnp/sp';

export interface ISiteInfoWebPartProps {}

export default class SiteInfoWebPart extends BaseClientSideWebPart<ISiteInfoWebPartProps> {
  public render(): void {
    this.getCurrentSiteInfo();
  }

  private async getCurrentSiteInfo(): Promise<void> {
    try {
      const site = await sp.site.get();
      this.domElement.innerHTML = `<div><strong>Site Collection URL:</strong> ${site.Url}</div>`;
    } catch (error) {
      this.domElement.innerHTML = "<div>Error fetching site information.</div>";
    }
  }
}

Conclusion

In this article, we covered 10 different examples of how to retrieve the current site collection context and URL in SharePoint Online using SPFx. You can utilize these methods in your custom web parts and extensions to enhance the functionality of your SharePoint solutions.

Remember to leverage the powerful SharePoint REST API and PnPjs to streamline your development process and improve the efficiency of your SPFx solutions. These examples can be extended further depending on the complexity of the solution you are building.

By combining these techniques, you can create more dynamic and context-aware SharePoint web parts tailored to your users’ needs.

Edvaldo Guimrães Filho Avatar

Published by