BlogSalesforce

Introduction to Lightning Message Service

By August 4, 2020 August 18th, 2020 No Comments

Salesforce developers rejoice! There is now a standardized way to communicate between Lightning Web Components (LWC), Aura Components, and, yes, even Visualforce Pages. The new capability is called Lightning Message Service, LMS, for short. To help you understand how it works, I’d like to provide a basic example of how to use the service.

For an organization hesitant to migrate to Lightning Experience and its newer technologies, Aura Components and Lightning Web Components, LMS may make the migration palatable. With LMS’s ability to communicate between Visualforce pages and lighting components, you can take a more disciplined approach to upgrading. Instead of scrapping existing Visualforce pages and creating new Lightning components, you can update existing Visualforce pages to interact with new Lightning components to provide new functionality.

Lightning Message Service does have limitations, though. You cannot use LMS under the following conditions:

  • AppExchange
  • Salesforce Mobile
  • Communities

To some degree, LMS is like Application Events for Aura Components. With an Application Event, you define an Aura Event component that contains the fields that store the data passed as part of the event. You can then use it to pass events to components that have registered for the event. In LMS, the equivalent is a Message Channel, which is a new metadata type, not a component. It has tags that define the name and data fields for the event.

Message Channels

The first step is to create a Message Channel, most easily done using VS Code and the Salesforce CLI. The first step is to create a new folder, messageChannels, in the force-app/main/default folder. Within that folder, create a new file with “.messageChannel-meta.xml” as the extension. The contents of the file should be similar to the following:

<?xml version="1.0" encoding="UTF-8"?>
        <fieldName>messageText</fieldName>

<LightningMessageChannel xmlns="http://soap.sforce.com/2006/04/metadata">
    <masterLabel>SampleMessageChannel</masterLabel>
    <isExposed>true</isExposed>
    <lightningMessageFields>
        <description>Holds the message to display</description>
    </lightningMessageFields>
</LightningMessageChannel>

The masterLabel tag is followed by the name for the message channel; in this case, “SampleMessageChannel.” The lightningMessageField tag defines the fields that will carry the event payload. Use multiple lightningMessageField tags if you need more than one field in the event payload. The isExposed tags allow the channel to be used across namespaces.

Once the message channel file is complete, deploy it to your org. Now, you are ready to make use of the message channel.

Publishing to a Message Channel

For this blog, LWC’s will be used to demonstrate how to use LMS. The first component will be the “publisher.” In the component’s Javascript file, you will need to start by importing the elements needed from the lightning/messageService module and the previously defined messageChannel. For this example, we will need publish and MessageContext from the messageService.

import messageChannel from '@salesforce/messageChannel/Sample__c';
import {publish, MessageContext} from 'lightning/messageService'

After the imports, create the message context. You can accomplish this using the createMessageContext() method or, if the component extends LightningElement, by using the following syntax:

@wire(MessageContext)
    messageContext;

Now, set up is complete to publish to the Message Channel. All that is needed now is to make a call to “publish.”

publish(this.messageContext, messageChannel, message);

The publish method takes three arguments: the message context, the message channel, and the message itself. The message is an object that contains the fields defined in the Message Channel file.

let message = {messageText: 'This is a test'};

Publishing an event is that simple. Here is the full text of the publishing component. Note, in this example, the pressing of a button on the UI triggers the publishing.

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

export default class Publisher extends LightningElement {

    @wire(MessageContext)
    messageContext;

    handleButtonClick() {
        let message = {messageText: 'This is a test'};
        publish(this.messageContext, messageChannel, message);
    }
}

Subscribing to a Message Channel

Now let’s take a look at the receiving (subscriber) end. Like the publisher, the subscribing module needs to import the message channel and the appropriate elements of the message service, in this case: subscribe and MessageContext.

import messageChannel from '@salesforce/messageChannel/Sample__c';
import { subscribe, MessageContext } from 'lightning/messageService';

A message context is also required, just like in the publishing component.

@wire(MessageContext)
    messageContext;

Lastly, you need to create the subscription. The subscribe method that was imported is used for this purpose. It takes three arguments: the message context, the message channel, and callback to be executed when an event is received on the message channel.

this.subscription = subscribe(this.messageContext, messageChannel, (message) => {
            console.log(message.messageText);
        });

That’s it! These two components now communicate using LMS. Here is the full text of the subscribing component:

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

export default class Subscriber extends LightningElement {

    subscription = null;

    @wire(MessageContext)
    messageContext;

    connectedCallback() {
        this.handleSubscribe();
    }

    handleSubscribe() {
        if (this.subscription) {
            return;
        }
        this.subscription = subscribe(this.messageContext, messageChannel, (message) => {
            console.log(message.messageText);
        });
    }
    
}

Resources

  1. Documentation to use LMS with LWCs
  2. Documentation to use LMS with Aura Components
  3. An example implementation of VisualForce

Next Steps

Do you need help building and implementing components in your Salesforce solution or leveraging the platform to serve your business better? We’re happy to share how we can help. Contact our team today.

Scott Byrd

Scott Byrd

Scott is a Senior Developer working from Soliant's Philadelphia office. He is a certified Salesforce Admin and Platform Developer I and has an MS in Information Systems and a BS in Computer Information Systems. Scott is an avid birdwatcher with a life list of over 400 species and counting.

Leave a Reply

Need to adjust your business processes quickly? We're helping clients use technology to keep their teams productive and running smoothly in these times of uncertainty. Our team can guide yours if you need help in these areas.

Talk to a Consultant