Lightning message service , Lightning message services in LWC

Lightning Message Service in LWC

Lightning Message Service in LWC with Pashtek– The Lightning Message Service (LMS) allows communication between Visualforce and Lightning Components (Aura and LWC both) on any Lightning page. No need to call any references in the component page.

We can receive the data by subscribing the LMS service. We can create Lightning Message Channel.

Step1: Create a Message Channel by using below code:

LMSChannel.messageChannel-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
   <LightningMessageChannel  
  xmlns="http://soap.sforce.com/2006/04/metadata">
    <description>This is a channel which is used by LWC component to   
            send data</description>
      <isExposed>true</isExposed>
      <lightningMessageFields>
        <description>This is the Id of the record</description>
        <fieldName>recordId</fieldName>
      </lightningMessageFields>
      <lightningMessageFields>
        <description>This is the  of the record</description>
        <fieldName>name</fieldName>
      </lightningMessageFields>
      <masterLabel>AccountData</masterLabel>
   </LightningMessageChannel>

Step2: After creating the message channel, we need to create a source component for sending the data. We gonna use this file in receiver component.

lightningMessagingService.html

 <template>
    <div class="Test">
        <h1 style='font-size:15px'> Sender!</h1>
        <template if:true={chatStarted}>
 
            <h1>Message From Client!</h1>
            <template for:each={recievedMessage} for:item="message">
                <strong key={message}   
  style="display:inline-block;margin-left:4cm">{message}</strong><br   
  key={message}>
 
            </template>
        </template>
 
        <textarea rows="2" cols="33" class="inputbox" value={inputValue2}   
  style='display:inline-block'
            label="Enter message to publish" 
  onkeyup={inputHandler}></textarea><button label="Publish" class="icon"
            onclick={publishMessage}>
            <span>-></span>
        </button><br>
 
    </div>
  </template>

lightningMessagingService.js

 
  import { LightningElement,wire,api,track } from 'lwc';
  import { NavigationMixin } from 'lightning/navigation';
  import SAMPLEMC from "@salesforce/messageChannel/LMSChannel__c"
  import {subscribe, MessageContext, APPLICATION_SCOPE, unsubscribe,   
  publish} from 'lightning/messageService'
  export default class LightningMessagingService extends    
  NavigationMixin(LightningElement) {
    inputValue;
    
   publishMessage(){
             const message={
            lmsData:{
                value:this.inputValue
            }
        }
          publish(this.context, SAMPLEMC, message);
          this.senderMsg.push(this.inputValue);
        this.chatStarted=true;
 
    }
 
  }

LightningMessagingService.css(Optional)

 .Test{
 
    color:rgb(0, 51, 255);
    background-color:white;
    border:1px solid rgb(209, 194, 194);
    border-radius:5px;
   
    box-shadow: inset 0px 0px 5px 1px #DBA632;
    text-align: center;
    padding:50px;
   
    width:9cm;
   
   
  }
 
  .icon{
   
    background-color:rgb(0, 250, 125);
    padding:8px;
    border-radius:50%;
    font-weight: bolder;
    font-size: large;
    color:white;
    border:2px solid yellow;
    display:inline;
   
    margin-left:5cm;
   
  }
  .icon:hover{
 
    background-color:blue;
 
  }
 
  .inputbox{
    margin-top: 4cm;
   display:inline;
  }

LightningMessagingService.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__AppPage</target>
        <target>lightning__HomePage</target>
        <target>lightning__RecordPage</target>
    </targets>
  </LightningComponentBundle>

Step3: To create a receiver component for receiving the data.

lmsReceiver.html

 <template>
     <div class="Test">
        <div>
            <h1 style='font-size:15px'>Message From Sender!</h1>
            <template for:each={recievedMessage} for:item="message">
                <strong key={message}  
    style="display:inline-block;">{message}</strong><br key={message}>
 
            </template>
            <template for:each={senderMsg} for:item="msg">
                <strong key={msg} 
   style="display:inline-block;margin-left:4cm">{msg}</strong><br   
   key={msg}>
 
            </template>
       </div>
    </div>
  </template>

lmsReceiver.js

 import { LightningElement,wire,track  } from 'lwc';
  import SAMPLEMC from "@salesforce/messageChannel/LMSChannel__c"
 
  import {subscribe, MessageContext, APPLICATION_SCOPE,   
          unsubscribe,publish} from 'lightning/messageService';
  export default class LmsReceiver extends LightningElement {
    @track recievedMessage=[];
      
    
    subscription
    
    @wire(MessageContext)
    context
 
    connectedCallback(){
        this.subscribeMessage()
    }
 
    subscribeMessage(){
        console.log('subscribeMessage');
        //I get above Console Log but handleMessage is not executing
        subscribe(this.context, SAMPLEMC,   
                 (message)=>{this.handleMessage(message)},  
                                         {scope:APPLICATION_SCOPE})
    }
 
    handleMessage(message){
        console.log('handleMessage');
        this.recievedMessage.push(message.lmsData.value?  
                message.lmsData.value :'NO Message published');
       
    }

lmsReceiver.css(optional)

.Test{
 
    color:rgb(0, 17, 255);
    background-color:white;
    border:1px solid rgb(209, 194, 194);
    border-radius:5px;
    box-shadow: inset 0px 0px 5px 1px #DBA632;
   
    padding:50px;
   
    width:9cm;
   height: 10cm;
   
  }

lmsReceiver.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__AppPage</target>
        <target>lightning__HomePage</target>
        <target>lightning__RecordPage</target>
    </targets>
   </LightningComponentBundle>

Output: