Sharing is caring!
Introduced in the Winter ’20 release by Salesforce, Lightning Message Service is the out-of-the-box functionality that empowers you to communicate between Visualforce and Lightning Components, including Aura web components (AWC) and Lightning web components (LWC).
LMS is defined as the standard publish-subscribe library that enables communication quickly and seamlessly with DOM across the Salesforce UI tech stack, including Visualforce Pages, Aura components, and Lightning Web Components (LWC) using simple API. With this unique feature of Salesforce, you can publish messages and subscribe to them anywhere within the lightning page. Lightning Message Service feature is similar to Aura application events that enable seamless communication between components.
Lightning Message Service is based on Lightning Message Channels, a new metadata type. Lightning Message Channel is used to access the Lightning Message Service API and Lightning Message Channel in LWC via scoped module @salesforce/messageChannel. When it comes to Visualforce, you can use the global variable $MessageChannel. In Aura, you can use lightning:messageChannel in your component.
Uses Of Lightning Message Service
- To enable communication between Visualforce page, Lightning web components, and Aura components,
- To access Lightning Message Service API for publishing messages throughout Lightning Experience. Also, it helps in subscribing to messages that originated from anywhere within Lightning Experience via Lightning Message Channel.
- A specific namespace is associated with Lightning Message Channel. Developers can choose whether they want their message channel to be available to other namespaces or not, ensuring the security of communication on Lightning Message Service.
Benefits Of Lightning Message Service
- One of the significant benefits is increased development time. For instance, if a Visualforce Page or Lightning component tries to reference a message channel that is non-available and that message channel is not exposed, then the code would not compile.
- This messaging service offers referential integrity between the code that references them and the message channel. It restricts the deletion of message channels, which are referenced by other codes. Further, Lightning Message Service supports auto-adding message channels to packages.
- As the metadata type is packageable, you can associate a message channel to a particular namespace and make it available/unavailable to other namespaces.
How To Use Lightning Message Service?
Lightning Message Service is based on a new type of metadata called Lightning Message Channels, which are lightweight, packageable components that you can create in your organization during runtime for publishing and subscribing to messages on them.
Structure For Lightning Message Channel
<?xml version=”1.0″ encoding=”UTF-8″?>
<LightningMessageChannel xmlns=”http://soap.sforce.com/2006/04/metadata”>
<description>This is a sample Lightning Message Channel.</description>
<isExposed>true</isExposed>
<lightningMessageFields>
<description>This is the data</description>
<fieldName>data</fieldName>
</lightningMessageFields>
<masterLabel>SampleMessageChannel</masterLabel>
</LightningMessageChannel>
- masterLabel is the only required field that identifies the message channel in various UIs.
- Exposed is the optional boolean field that declares false if you don’t specify it. Also, this field tells our system whether or not a specific message channel is available to components in other namespaces.
Where Do We Make A Lightning Message channel In Our Org?
- Use VsCode, then use the Salesforce CLI and SFDX project.
- Create a folder “messageChannels” in “force-app\main\default\.”
- In “messageChanel” directory <channelName>.messageChannel-meta.xml E.g., SampleMessageChannel.messageChannel-meta.xml.
- Deploy the message channel to your organization to know about your message channel and then use it in your code.
- Message channel in another namespace that can be used with the namespace followed by two underscores. So if SampleMessageChannel was from the example namespace, you’d say example__SampleMessageChannel__c.
How To Implement Lightning Message Service?
Using Lightning Message Service with VisualForce:
For Visualforce, we can use Global variable $MessageChannel
var SAMPLEMC = “{!$MessageChannel.SampleMessageChannel__c}”;
var subscriptionToMC;
function onMCPublished(message) {
var textArea = document.querySelector(“#MCMessageTextArea”);
textArea.innerHTML = message ? JSON.stringify(message, null, ‘\t’) : ‘no message payload’;
}
function subscribe_Message_Channel() {
if (!subscriptionToMC) {
subscriptionToMC = sforce.one.subscribe(SAMPLEMC, onMCPublished);
var divAr = document.querySelector(“#subscMessage”);
divAr.innerHTML = ‘Subscribed : True!’;
var divAr = document.querySelector(“#unsubscMessage”);
divAr.innerHTML = ”;
}
}
function unsubscribe_Message_Channel() {
if (subscriptionToMC) {
sforce.one.unsubscribe(subscriptionToMC);
subscriptionToMC = null;
var divAr = document.querySelector(“#unsubscMessage”);
divAr.innerHTML = ‘Subscribed : False! ‘;
var divAr = document.querySelector(“#subscMessage”);
divAr.innerHTML = ”;
}
}
function publishMC() {
const payload = {
Data: { value: “Sample Message”,
channel: ‘SampleChannel’,
source: ‘VF’ }
};
sforce.one.publish(SAMPLEMC, payload);
}
The __c convention at the end of the message channel name in code denotes a custom message channel created on the Platform, but there is no other connection to custom objects.
Using Lightning Message Service with Aura component:
For Aura component, Use lightning:messageChannel in your component,
To receive messages on a message channel from anywhere in the application, use lightning:messageChannel’s optional parameter, scope. Set scope to the value “APPLICATION.”
We can publish and subscribe to the message in the same component as well if we use lightning:messageChannel with attribute scope= “APPLICATION.”
handleMessage : function(component, message, helper) {
try{
if(message.getParam(‘Data’)){
component.set(‘v.messageFromPublisher’,JSON.stringify(message.getParam(‘Data’)));
}
}
catch(exp){
console.log(exp.message);
}
},
publishMC: function(component, event, helper) {
try{
let payload = {
Data: { value: “Sample Message”,
channel: ‘SampleChannel’,
source: ‘Aura’ }
};
component.find(“sampleMessageChannel”).publish(payload);
} catch (error) {
console.log(`Error—${error}`);
}
}
For LWC, To reference a message channel in LWC, import it from the new @salesforce/messageChannel scoped module. To use the LMS APIs, import the functions we’re interested in — publish, subscribe, unsubscribe, etc. — from lightning/messageService.
Here’s an example using publish, subscribe and unsubscribe. You can assume that the publishMC, subscribeMC, and unsubscribeMC function below is bound to a button click in the template, and the receivedMessage property is bound to a textarea.
import { LightningElement,track } from ‘lwc’;
import { createMessageContext, releaseMessageContext,
subscribe, unsubscribe,publish } from ‘lightning/messageService’
import SAMPLEMC from “@salesforce/messageChannel/SampleMessageChannel__c”;
export default class LMS_DEMO_LWC extends LightningElement {
context = createMessageContext();
subscription = null;
@track receivedMessage = ”;
publishMC() {
let message = {
Data: { value: “Sample Message”,
channel: ‘SampleChannel’,
source: ‘LWC’ }
};
publish(this.context, SAMPLEMC, message);
}
subscribeMC() {
if (this.subscription) {
return;
}
this.subscription = subscribe(this.context, SAMPLEMC, (message) => {
this.handleMessage(message);
});
}
unsubscribeMC() {
unsubscribe(this.subscription);
this.subscription = null;
}
handleMessage(message) {
this.receivedMessage = message ? JSON.stringify(message, null, ‘\t’) : ‘no message payload’;
}
disconnectedCallback() {
releaseMessageContext(this.context);
}
}
The createMessageContext and releaseMessageContext functions are unique to LWC. The context object provides contextual information about the Lightning Web Components using LMS. In disconnectedCallback, our recommendation is to call releaseMessageContext, which will unregister any subscriptions associated with the context.
Limitations For Lightning Message Services
Lightning Message Service supports only the following experiences:
- Lightning Experience standard navigation.
- Lightning Experience console navigation.
- Salesforce mobile app for Aura and Lightning Web Components, but not for Visualforce pages.
- Lightning components used in Experience Builder sites. Support for Experience Builder sites is beta
Aura components that don’t render aren’t supported
The Lightning Message Service supports only the rendered Aura components. You can’t use lightning:messageChannel in an Aura component that uses the background utility item interface. Similarly, Aura components that use lightning:messageChannel can’t call Lightning Message Service methods in the init lifecycle handler because the component hasn’t rendered.
lightning:messageChannel must be a child of aura:component
In a custom Aura component, lightning:messageChannel must be an immediate child of the aura:component tag. It can’t be nested in an HTML tag or another component.
For example, the following code renders without a problem.
- <aura:component>
- <lightning:messageChannel type=”myMessageChannel__c” />
- <lightning:card>…</lightning:card>
- </aura:component>
This code throws an error when the Aura component tries to render.
- <aura:component>
- <lightning:card>
- <lightning:messageChannel type=”myMessageChannel__c” />
- </lightning:card>
- </aura:component>
Here a link for a video of their LMS working between Aura, LWC, Visualforce page:
https://drive.google.com/file/d/1eYC2sFUagAuzAnp8Ric_AO-mkylMNIlH/view?usp=sharing
Final Wrap
LMS, a front-end solution in Salesforce, operates in client-side UI and supports popped-out utility bar item windows with parent/child iFrame windows (related to Visualforce). By using Lightning Message Service(LWS), you can create basic components. You can use the same approach to pass data between components. With Lightning Message Service, you no longer need to set up a Sub-Pub module to pass data between different components.
To stay on top of the Salesforce CRM platform and learn how to make the most out of it? Subscribe to our YouTube channel now to get the latest news and updates on CRM, Salesforce, Google Cloud, Cloud Computing, and more. Need help getting started with Salesforce development, integration, Salesforce customization? Get in touch with Cloud Analogy, the best Salesforce app development company now!
Akshay Dhiman
Chief Technical Officer
Akshay Dhiman, the CTO of Cloud Analogy, has been a standout and successful Salesforce Platform Developer for years. He has a rich experience in Salesforce Integration, JavaScript, APEX, VisualForce, Force.com Sites, Batch Processing, Lightning, PHP, C++, Java, NodeJs, ReactJs, Angular 8, GraphQL, React Native, Web Technology, and jQuery.Hire the best Salesforce Development Company. Choose certified Salesforce Developers from Cloud Analogy now.