Determine The Origin Of A Lightning Web Component (LWC)

Situation

Frequently, we encounter situations where a Lightning Web Component (LWC) needs to exist both within a community for external users and the app builder for internal users. Let’s explore a method to determine the component’s source of access, enabling conditional rendering of design/CSS.

To achieve this, we’ll leverage the connectedCallback() lifecycle hook to retrieve information from an Apex class and integrate it into the LWC’s JavaScript.

Sample Code:

identifysource.html

<template>
    {isincommunity}
</template>

identifysource.js

import { LightningElement,track } from 'lwc';
import checkPortalType from '@salesforce/apex/IdentifySource.checkPortalType';
export default class Identifysource extends LightningElement {
    @track isincommunity;
    connectedCallback(){
        checkPortalType()
            .then(result => {
                var isInPortal = result === 'Theme3' ? true : false;
                //setting tracked property value
                this.isincommunity = isInPortal;
            })
            .catch(error => {
                this.error = error;
        });
    }
}

IdentifySource.cls

public with sharing class IdentifySource {
    @AuraEnabled
    public static String checkPortalType() {
        return UserInfo.getUiThemeDisplayed();
    }
}
Context

If you come from an Aura background, you can draw a parallel between the connectedCallback() and the doInit() methods. To execute any logic before the element renders, incorporate it into the connectedCallback() method. This lifecycle hook activates when a component is inserted into the DOM and operates from parent to child in the Lightning Web Component structure. Therefore, we invoke the apex from the connectedCallback() method.

On the apex side, the UserInfo class is utilized to fetch the UI Theme of the currently logged-in user. This approach allows us to discern the theme under which the user has logged in. The output of the getUiThemeDisplayed() method is illustrated below:

  • Theme1: Obsolete Salesforce theme
  • Theme2: Salesforce Classic 2005 user interface theme
  • Theme3: Salesforce Classic 2010 user interface theme
  • Theme4d: Modern “Lightning Experience” Salesforce theme
  • Theme4t: Salesforce mobile app theme
  • Theme4u: Lightning Console theme
  • PortalDefault: Salesforce Customer Portal theme
  • Webstore: Salesforce AppExchange theme