Enhancing Object-based Lightning Message Service

Enhancing Object-based Lightning Message Service

Information:-

Lightning Message Service (LMS) is a robust tool within Salesforce that enables communication between various components, such as Visualforce and Lightning components (both Aura and Lightning Web Components). It allows you to create a seamless interaction across any Lightning page, making it easier for components to share information. The LMS API allows you to publish and subscribe to messages throughout the Lightning Experience, facilitating a similar experience to Aura Application Events.

One of the core elements of LMS is the Lightning Message Channel, which serves as a communication pathway. You can leverage this to build dynamic, responsive applications that seamlessly bridge different component types, such as Visualforce and LWC.

Core LMS Features:-

  • Cross-component Communication: LMS provides communication between components like Visualforce, Aura, and Lightning Web Components (LWC) on the same page.
  • Message Publication and Subscription: LMS API facilitates publishing messages and subscribing to these messages across different components, enabling data synchronization and interactivity.

How to Access LMS in Different Frameworks:

  1. Lightning Web Components (LWC): Use the scoped module @salesforce/messageChannel to access LMS.
  2. Visualforce: Leverage the global variable $MessageChannel.
  3. Aura: Use lightning:messageChannel in your Aura component to work with LMS.

When to Use Lightning Message Service:

LMS is particularly useful when you need a Visualforce page to communicate with a Lightning Web Component. Previously, you would have had to implement a custom publish-subscribe solution since LWC events can’t handle cross-framework communication. With LMS, this gap is bridged, and you can easily facilitate this interaction.

Steps to Create Lightning Message Service:-

  • Create a Message Channel: Using the Metadata API, create a message channel named SampleMessageChannel__c. This channel will be the central hub for communication between the components.

  • Publisher Lightning Web Component: Create a Lightning Web Component called publisherComponent. This component will publish messages to the SampleMessageChannel__c.

 

PublisherComponent.js

import { LightningElement, wire } from ‘lwc’;

import { publish, MessageContext } from ‘lightning/messageService’;

import SAMPLEMC from “@salesforce/messageChannel/SampleMessageChannel__c”;

export default class PublisherComponent extends LightningElement {

 @wire(MessageContext)

   messageContext;

   handleClick() {

        const message = {

            recordId: “Any string”,

            recordData: {

             value: “any data”

            }

        };

        publish(this.messageContext, SAMPLEMC, message);

    }

}

In this example, handleClick() sends a message payload containing the recordId and recordData when the publish button is clicked.

PublisherComponent.html Code:-

<template>

    <lightning-card title=”MyLwcPublisher” icon-name=”custom:custom14″>

        <div class=”slds-m-around_medium”>

            <p>MessageChannel: SampleMessageChannel</p>

            <br>

            <lightning-button label=”Publish” onclick={handleClick}></lightning-button>

        </div>

    </lightning-card>

</template>

The HTML template defines the UI for the component, including a publish button that triggers the message publication on click.

Subscribing in Visualforce Page: Once the message is published by the LWC component, a Visualforce page can subscribe to this message using $MessageChannel.

Lightning Web Component Code:-

<apex:page>

    <div>

        <p>Subscribe to SampleMessageChannel</p>

        <button onclick=”subscribeMC()”>Subscribe</button>

        <p>Unsubscribe from SampleMessageChannel</p>

        <button onclick=”unsubscribeMC()”>Unsubscribe</button>

        <br/>

        <br/>

        <p>Received message:</p>

        <textarea id=”MCMessageTextAreaId” rows=”10″   style=”disabled:true;resize:none;width:100%;”/>

    </div>

    <script>

        // Load the MessageChannel token in a variable

        var SAMPLEMC = “{!$MessageChannel.SampleMessageChannel__c}”;

        var subscriptionToMC;

        function onMCPublished(message) {

            var textArea = document.querySelector(“#MCMessageTextAreaId”);

            textArea.innerHTML = message ? JSON.stringify(message, null, ‘\t’) : ‘no message payload’;

        }

        function subscribeMC() {

            if (!subscriptionToMC) {

                subscriptionToMC = sforce.one.subscribe(SAMPLEMC, onMCPublished, {scope: “APPLICATION”});

            } 
  }

        function unsubscribeMC() {

            if (subscriptionToMC) {

                sforce.one.unsubscribe(subscriptionToMC);

                subscriptionToMC = null;

            }

        }

    </script>

</apex:page>

 

This Visualforce page subscribes to SampleMessageChannel__c and displays the received message in a textarea. It also offers the option to unsubscribe when needed.

Benefits Of Using Lightning Message Service (LMS):-

1. Cross-Framework Communication

LMS enables seamless communication between different component types (Visualforce, Aura, and Lightning Web Components) on the same Lightning page. This eliminates the need for custom publish-subscribe solutions.

2. Simplified Communication Architecture

LMS removes the complexity of building communication channels between components, offering a standard API for message exchange. This simplifies the architecture and makes development more efficient.

3. Reusability

The same Lightning Message Channel can be reused across multiple components and pages, which reduces redundancy and simplifies maintenance.

4. Decoupled Components

LMS promotes decoupled component design, allowing components to communicate without being directly tied to each other. This enables better modularity and maintainability.

5. Consistency Across Platforms

Whether you’re using Visualforce, Aura, or Lightning Web Components, LMS provides a consistent method for inter-component communication, ensuring that developers can use a unified approach regardless of the platform.

6. Enhanced User Experience

By enabling smooth communication between components, LMS allows real-time updates and interactions, which leads to a more responsive and dynamic user interface.

7. Reduced Dependency on Custom Events

Instead of relying on custom events or handling complex DOM manipulations, LMS leverages message channels that simplify the publish-subscribe model for better efficiency and readability in the code.

8. Secure Communication

LMS provides secure, scoped message communication. By using predefined message channels, you can limit the scope of communication to only relevant components, enhancing data privacy and security.

Summary:-

Lightning Message Service (LMS) significantly enhances communication between Visualforce and Lightning components by enabling cross-component interaction via Lightning Message Channels. The LMS API is a powerful tool that mimics the behavior of Aura Application Events, allowing for more integrated and dynamic applications.

Key steps to implement LMS include creating a message channel, publishing messages from a Lightning Web Component, and subscribing to those messages in other components, such as Visualforce. This opens new possibilities for creating fluid, interactive experiences within Salesforce.

 

Contact Us

We would love to hear from you Please feel free to send us a message via the form