Lightning

Events in Lightning Component and Visualforce page using Lightning Message Service (LMS)

Events in Lightning Component and Visualforce Pages using Lightning Message Channel

Consider a scenario where you are working on multiple components and in which there are Visualforce pages, Lightning Aura Components, Lightning Web Components. We know that we have Lightning Aura Events (Application Event and Component Event) which works in Lightning Aura Component. But what if there is a scenario where you want to send an event across component whether it is between Aura Component or a Web Component or a Visualforce page. Or combination of all three.

Salesforce has introduced Lightning Web Component Message Service (lightning-message-service). It is used to communicate across the DOM between Visualforce pages, Aura components, and Lightning web components, including components in a pop-out utility bar. To communicate across DOM there should be a channel. And salesforce has provided Lightning Message Channel to communicate.

You must import both message service (lightning/messageService) and message channel (@salesforce/messageChannel) to get things working.

Click here to know how to create Lightning Message Channel.

In this blog we will see how we can communicate from a Lightning Web Component (LWC) to Lightning Aura Component (LAC). First, we will see LWC code. Followed by LAC.

  • Lightning Message Channel

Sample_MessageChannel.messageChannel-meta.xml

<?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>Variable 1</description>
        <fieldName>variable1</fieldName>
    </lightningMessageFields>
    <masterLabel>Sample Message Channel</masterLabel>
</LightningMessageChannel>

  • Lightning Web Component

Test_LWC.html

<template>
    <div class="slds-box slds-theme_default">
        <lightning-card  variant="Narrow"  title="This is Lightning Web Component" icon-name="standard:account">
            <p class="slds-p-horizontal_small">
                <lightning-button variant="neutral" class="slds-p-around_xx-small" label="Red" title="Red" onclick={handleRedClick}></lightning-button>
                <lightning-button variant="neutral" class="slds-p-around_xx-small" label="Green" title="Green" onclick={handleGreenClick}></lightning-button>
                <lightning-button variant="neutral" class="slds-p-around_xx-small" label="Blue" title="Green" onclick={handleBlueClick}></lightning-button>
            </p>
        </lightning-card>
    </div>
</template>

test_LWC.js

import { 
    LightningElement
} from 'lwc';

import { publish, createMessageContext, MessageContext, subscribe, unsubscribe } from 'lightning/messageService';
import a_LMS_Channel from "@salesforce/messageChannel/Sample_MessageChannel__c";

export default class test_LWC extends LightningElement {

    //LMS Services
    context = createMessageContext();

    handleRedClick(event){
        console.log('In LWC: Red button clicked');
        

        let message = {
            Data: { 
                value: "Red",
                channel: 'SampleChannel',
                source: 'LWC' 
            }
        }
        publish(this.context, a_LMS_Channel, message);
    }

    handleGreenClick(event){
        console.log('In LWC: Green button clicked');
        let message = {
            Data: { 
                value: "Green",
                channel: 'SampleChannel',
                source: 'LWC' 
            }
        }
        publish(this.context, a_LMS_Channel, message);
    }

    handleBlueClick(event){
        console.log('In LWC: Blue button clicked');
        let message = {
            Data: { 
                value: "Blue",
                channel: 'SampleChannel',
                source: 'LWC' 
            }
        }
        publish(this.context, a_LMS_Channel, message);
    }
}

You need to import lightning/messageService

import { publish, createMessageContext, MessageContext, subscribe, unsubscribe } from 'lightning/messageService';

Also the channel that you have created newly in 1st step

import a_LMS_Channel from "@salesforce/messageChannel/Sample_MessageChannel__c";

You need to mention the context of the service

//LMS Services
context = createMessageContext();

test_LWC.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>52.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
        <target>lightning__AppPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>

  • Lightning Aura Component

Test_LAC_Component.cmp

<aura:component implements="flexipage:availableForRecordHome,flexipage:availableForAllPageTypes">
    
    <lightning:messageChannel type="Sample_MessageChannel__c" aura:id="Sample_MessageChannel_Channel" onMessage="{!c.a_Modal_Color}"/>
    <aura:attribute name="a_Color" type="String" access="global" default="No" />
	<div  class="slds-p-around_small">
        <lightning:card footer="Card Footer" title="This is Lightning Aura Component">
        
        	<p class="slds-p-horizontal_small">
            	<c:test_LWC />
        	</p>
            <aura:set attribute="footer">
            	User has clicked <b> {!v.a_Color} </b> button.
            </aura:set>
    	</lightning:card>
    </div>
</aura:component>

Define the lightning:messageChannel and call an action when a message is received

<lightning:messageChannel type="Sample_MessageChannel__c" aura:id="Sample_MessageChannel_Channel" onMessage="{!c.a_Modal_Color}"/>

Test_LAC_ComponentController.js

({
    a_Modal_Color : function(component, message, helper) {
        var a_Color = message.getParam('Data').value;
        component.set("v.a_Color",a_Color); 
	}
})

Here when defining a function you need to include message (same as event) attribute and use message attribute you can read the object sent.

message.getParam('Data').value;

Output

Nothing Clicked

Red Clicked

Green Clicked

Blue Clicked


Note:

The Lightning message service supports only the following experiences:

  1. Lightning Experience standard navigation
  2. Lightning Experience console navigation
  3. Salesforce mobile app for Aura and Lightning Web Components, but not for Visualforce pages
  4. Lightning components used in Experience Builder sites. Support for Experience Builder sites is beta.
  5. Lightning Message Service doesn’t work with Salesforce Tabs + Visualforce sites or with Visualforce pages in Experience Builder sites
  6. You can create Message Channel to communicate through Visual Studio only as of now using steps mentioned in my other post.

Resource:

Lightning Message Service Limitations

Message Channel

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s