Obtaining the Salesforce org base URL or Community base URL in Salesforce Lightning is crucial, given the numerous scenarios where accessing Salesforce/Community URLs is necessary.
What is the method for obtaining the Community URL in LWC?
Three distinct methods exist for obtaining the Community base URL in Lightning Web Component.
First Method – Utilize the Salesforce Module
The initial step involves utilizing the @salesforce module in LWC. This approach is beneficial and advisable when you’re certain that the component is exclusively employed within the Lightning Experience Community.
Import the following two properties of the Salesforce community into the Salesforce Lightning Component.
import networkId from '@salesforce/community/Id'; import basePath from '@salesforce/community/basePath';
Now use the below code where ever you want the base URL of your salesforce community
const before_ = `${basePath}`.substring(0, `${basePath}`.indexOf('/s')+1); const communityUrl = `https://${location.host}${before_}`;
Second Method – Employing the Network Class
Salesforce offers the Network class, which furnishes numerous standard methods for Salesforce Communities. This class proves highly beneficial in obtaining the community base URL.
Incorporate the following Apex method into your LWC Controller class.
@AuraEnabled(cacheable=true) public static String getOrgBaseUrl(){ String baseUrl = Network.getLoginUrl( Network.getNetworkId() ); return baseUrl; }
Utilize the @wire method to invoke the Apex class and store the URL in the private property of the JavaScript class.
import { LightningElement, track, wire } from 'lwc'; import getOrgBaseUrl from '@salesforce/apex/NetworkHelperClass.getOrgBaseUrl'; export default class NotificationComponent extends NavigationMixin(LightningElement) { communityBaseUrl; @wire(getOrgBaseUrl) wiredBaseUrl(result) { const { error, data } = result; if (data) { this.communityBaseUrl = `${data}`; } else if (error) { console.error('Error: ', error); } } }
Now utilize the communityBaseUrl variable wherever necessary within the JavaScript method to access the base URL of the Salesforce Community.
Third Method – Employ JavaScript Object
You can consistently employ a JavaScript location object to retrieve the host while the Lightning Web Component operates within Salesforce Communities.
The following code snippet will furnish the Salesforce Community base URL if the community path is “panther”.
const basePath = 'panther'; const communityUrl = `https://${location.host}$/{basePath}/`