How to Use Lightning Message Service (LMS) in Salesforce LWC? : Bijay Kumar

How to Use Lightning Message Service (LMS) in Salesforce LWC?
by: Bijay Kumar
blow post content copied from  SalesForce FAQs
click here to view original post



### Summary of Lightning Message Service (LMS) in Salesforce Lightning Web Components **Key Details:** - **Lightning Message Service (LMS)** is a framework in Salesforce that facilitates communication between different components such as Lightning Web Components (LWC), Aura components, and Visualforce pages without needing a direct parent-child relationship. - LMS is preferred over traditional methods like parent-child events because it allows for more flexible communication across components on a Lightning page. **Tutorial Overview:** 1. **Setting up LMS**: - Create a message channel folder and a meta.xml file to define the communication channel. - The XML code specifies the channel's properties and exposes it for use. 2. **Creating a Publisher Component**: - A parent component sends messages using the `publish` method from LMS. - The component includes an input field and a button that triggers the message sending when clicked. 3. **Creating a Subscriber Component**: - A child component listens for messages using the `subscribe` method. - It updates its display with the received message. 4. **Deploying Components**: - Both components must be placed on the same Lightning page for communication to work. **Conclusion**: By following the steps outlined, users can effectively set up and use LMS in Salesforce to enable inter-component communication, enhancing the functionality and user experience of their applications. ### Additional Context LMS plays a crucial role in modularizing Salesforce applications by enabling components to communicate without tightly coupling them. This flexibility helps in maintaining and scaling applications more efficiently. ### Relevant Hashtags for SEO #Salesforce #LightningWebComponents #LMS #SalesforceTutorial #WebDevelopment #ComponentCommunication #SalesforceDevelopment #LightningComponents #SalesforceLWC #TechTutorials


In Salesforce Lightning Web Components, the Lightning Message Service (LMS) is used to establish communication between Visualforce and Lightning Web Components on any lightning page without calling the reference. It is also used to set up communication between the LWC components not having a parent-child relationship.

In this Salesforce tutorial, we will learn how to use the Lightning Message Service (LMS) in Salesforce LWC.

What is Lightning Message Service (LMS) in Salesforce?

In Salesforcel, Lightning Message Service (LMS) is a framework that enables Lightning Web Components (LWCs) and other Salesforce components (like Aura components and Visualforce pages) to communicate with each other. The main use of LMS is to enable communication between multiple lightning web components.

The Lightning Message Service (LMS) is preferred over other communication methods, like parent-child events or Aura events, because it enables communication between Lightning Web Components (LWCs), Aura components, and Visualforce pages, regardless of hierarchical relationship. Unlike parent-child events that require a direct connection, LMS allows components to communicate across a page without needing a reference to each other.

Use Lightning Message Service (LMS) in Salesforce LWC

In the example below, we will see the method to implement the Lightning message service in lightning web components, and for that, we will cover the following points.

  • Create a message channel folder in the default folder for Lightning Message Service.
  • A Publisher(parent) component from where the message will be sent.
  • A Subscriber(child) component that receives the message.

Setup Message Channel Folder for the Lightning Message Service

In order to use the functionalities of the Lightning Message Service, it is necessary to establish a Lightning Message Channel.

To set up a message channel folder for the Lightning Message Service, follow the steps below.

1. Create a folder inside force-app>main> default and name it as messageChannels. Ensure the name is the same as the exact letter case. Inside the new folder, create a meta.xml file with the name ComponentCommunicationChannel.messageChannel-meta.xml.

How to use Lightning Message Service in Salesforce LWC

2. Enter the below code in the meta.xml file.

<?xml version="1.0" encoding="UTF-8"?>
<MessageChannel xmlns="http://soap.sforce.com/2006/04/metadata">    

<description>Channel for communication between ComponentA and ComponentB </description>
     <isExposed>true</isExposed>
     <masterLabel>Component Communication Channel</masterLabel>
</MessageChannel>

With the <MessageChannel> tag, this file will be accessible to manage the Lightning Message Service (LMS) API.

After setting up the message channel, make sure to deploy the folder to the source org.

Create a Publisher Component to Send a Message Using LMS

In the below steps, we will create a publisher (parent) component to send a message to the child component.

1. Create an LWC component and enter the below code in the JS file. Here, the communication channel is referenced with suffic “__c” because it indicates a custom metadata object in Salesforce.

import { LightningElement, wire } from 'lwc';
import { publish, MessageContext } from 'lightning/messageService';
import COMPONENT_COMMUNICATION_CHANNEL from '@salesforce/messageChannel/ComponentCommunicationChannel__c';

export default class ComponentPublisher extends LightningElement {
    @wire(MessageContext)
    messageContext;

    handleButtonClick() {
        const msgInput = this.template.querySelector('lightning-input').value;
        if (msgInput) {
            const payload = { message: msgInput };
            publish(this.messageContext, COMPONENT_COMMUNICATION_CHANNEL, payload);
        }
    }
}

To get the functionality of sending or publishing the message, we have imported publish and MessageContext, which contains information about the Lightning web component that is using the Lightning message service.

To connect the message service to the publisher component, we have used the @wire decorator. The message will be sent on the button click for that we have defined

After this, publish(this.messageContext, COMPONENT_COMMUNICATION_CHANNEL, payload) will send the message using the Lightning Message Service (LMS).

2. Enter the below code, to render the UI of the publisher component.

<template>
    <lightning-card title = "Component Publisher" >
        <div class="slds-m-around_medium">
            <lightning-input title="Enter message" label = "Enter message"></lightning-input>
            <lightning-button label = "Send Message" onclick={handleButtonClick}></lightning-button>
        </div>
    </lightning-card>
</template>

In the above code, the <lightning-input> will give an input field to enter the text. The <lightning-button> will show a button, and on click, it will trigger the handleButtonClick event and send the message.

3. Make the LWC component visible to the lightning pages using the code below in the meta.xml file inside the <LightningComponentBundle> tag.

 <isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>

After this, deploy the changes of the LWC component to the source org.

Create a Subscriber Component to Receive a Message Using LMS

In the below steps, we will create a subscriber (child) component to receive the message sent from the publisher component.

1. Create another LWC component and enter the code below in the JS file.

import { LightningElement, wire } from 'lwc';
import { subscribe, MessageContext } from 'lightning/messageService';
import COMPONENT_COMMUNICATION_CHANNEL from '@salesforce/messageChannel/ComponentCommunicationChannel__c';

export default class ComponentChild extends LightningElement {
    @wire(MessageContext)
    messageContext;

    subscription = null;
    receivedMessage = 'No message received'; 

    connectedCallback() {
        if (!this.subscription) {
            this.subscription = subscribe(
                this.messageContext,
                COMPONENT_COMMUNICATION_CHANNEL,
                (payload) => this.handleMessage(payload)
            );
        }
    }

    handleMessage(payload) {
        this.receivedMessage = payload.message; 
    }
}

This component subscribes to the ComponentCommunicationChannel and listens for messages sent via LMS. The connectedCallback() method ensures the subscription happens when the component is initialized.

When a message is received, the handleMessage() function updates the receivedMessage property, which is then displayed in the subscriber (child) component.

2. Enter the code below in the HTML file to display the received message.

template>
    <lightning-card title="Component Child">
        <div class = "slds-m-around_medium">
            <lightning-formatted-text value={receivedMessage}></lightning-formatted-text>
        </div>
    </lightning-card>
</template>

The value of “receivedMessage” will be displayed as the message received from the publisher component.

3. Enter the below code in the meta.xml file of the child component to expose it to the lightning pages.

<isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>

After this, deploy the component to the source org.

Navigate to the Lightning page and deploy both Lightning web components there. Ensure that both components are present on the same record page for the Lightning Message Service to function properly.

In the parent component, enter the text message and press the “Send Message” button. The child component will then receive the message and display the same text.

Use Lightning Message Service in Salesforce LWC

This way, we can use the Lightning Message Service (LMS) in Salesforce lightning web components to establish communication between the components with no relationship.

Conclusion

In this Salesforce tutorial, we have learned how to use the Lightning Message Service (LMS). To set it up, we created a Lightning Message Channel, defined a publisher component to send messages, and configured a subscriber component to receive them. By implementing LMS, we enabled communication between the components on a Lightning page, regardless of their hierarchical relationship.

By following the above steps, you can efficiently set up Lightning Message Service in your Salesforce org, and establish communication between the LWC components.

You may also like to read:

The post How to Use Lightning Message Service (LMS) in Salesforce LWC? appeared first on SalesForce FAQs.


April 01, 2025 at 10:35AM
Click here for more details...

=============================
The original post is available in SalesForce FAQs by Bijay Kumar
this post has been published as it is through automation. Automation script brings all the top bloggers post under a single umbrella.
The purpose of this blog, Follow the top Salesforce bloggers and collect all blogs in a single place through automation.
============================

Salesforce