How to Use Lightning Message Service (LMS) in Salesforce LWC

Lightning Message Service (LMS) is a powerful feature in Salesforce that allows communication between different components.

It helps developers send messages between Lightning Web Components (LWC), Aura components, and even Visualforce pages.

In Salesforce Lightning Web Components, the Lightning Message Service (LMS) enables communication between Visualforce and Lightning Web Components on any Lightning page without requiring a reference.

It is also used to establish communication between LWC components that do not have 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?

Lightning Message Service is used to communicate between components that are not directly related.

Example:

  • One component sends data
  • Another component receives it

Even if:

  • They are not parent-child
  • They are on different parts of the page

Key Components of LMS

  1. Message Channel
    • A file that defines message structure
    • Created in Salesforce
  2. Publisher
    • Sends message
  3. Subscriber
    • Receives message

In Salesforce, Lightning Message Service (LMS) is a framework that enables Lightning Web Components (LWCs) and other Salesforce components (such as Aura components and Visualforce pages) to communicate with one another.

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 relationships.

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 how to implement the Lightning message service in Lightning web components. To do so, 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.