How to detect if a SPFx Application Customizer is running inside Microsoft Teams

SharePoint Application customizers allow you to customize SharePoint further, giving you access to safe containers where you can add extra components to improve the out of the box experience. This type of customization is perfect for solutions that you want to make available in all modern pages within a site collection or even in the entire tenant.

All this is great but there is a twist when it comes to using SPFx Application customizers in the context of SharePoint pages rendered inside Microsoft Teams, if you want to change the behavior on this scenario or simply not load the extension at all, there are no straightforward way to detect the Teams context as we have with web parts.

Detect SPFx application customizer running inside Microsoft Teams

While developing a solution to display Microsoft Teams chat in SharePoint I faced the issue of having the chat appearing also inside Microsoft Teams when a page was added as a tab to a channel, so my goal was to render it only if the user was accessing SharePoint through the browser.

Here’s how I did it and how you can also implement something similar in your projects:

  1. Start by adding the Microsoft Teams client library to your SPFx project by running the following npm command
    npm install @microsoft/teams-js
  2. In the main typescript file add the following import
    import { app } from "@microsoft/teams-js";
  3. Make the onInit method async
    public async onInit(): Promise<void>
  4. At the top of the onInit method before executing any other code add the following
    try {
            await app.initialize();
            const context = await app.getContext();
              //The extension is running inside Microsoft Teams
          } catch (exp) {
              //The extension is running outside Microsoft Teams
  5. Adjust the code to your needs to make your extension behave properly when rendered inside Microsoft Teams.

If you are building a web part and need to detect the Teams context, there is no need to apply the solution described in this post, you can simply use what Microsoft has described in this article.

No comments yet

Leave a Reply

I've been working with Microsoft Technologies over the last ten years, mainly focused on creating collaboration and productivity solutions that drive the adoption of Microsoft Modern Workplace.

%d bloggers like this: