salesforceLMS


 LMS - Lightning Messaging Service 

  •    It is a way to communicate between unrelated Components.



  • Introduce In Winter 20 
  • We must use the Lightning Message Channel to access the Lightning Message Service API.
  • Ways to access Lightning Message Channel
  • In LWC we can access the Lightning Message Channel with the scoped module   @salesforce/messageChannel. 
  •  In Visualforce, we can use the global variable $MessageChannel. 
  •  In Aura, use lightning:messageChannel in your component.
  • Create message channel definition with the suffix .messageChannel-meta.XML
  • You can communicate across Dom but within the same lightning page.
  • You can also use Lightning message service to communicate with softphones via Open CTI.

You need to create a Message Channel in Visual Code and create a folder named messageChannels



Following is way to create a Message Channel 

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

<LightningMessageChannel xmlns="http://soap.sforce.com/2006/04/metadata">

    <description>This is Lightning Message Channel</description>

    <isExposed>true</isExposed>

    <lightningMessageFields>

        <description>Channel</description>

        <fieldName>VariableName</fieldName>

    </lightningMessageFields>

    <masterLabel>Message Channel</masterLabel>

</LightningMessageChannel>

Note :

  • I have created new Object LMS  
  • MsgVariable__c  is Message Channel Name 
  • VariableName is MessageChannel Field Name .

Visualforce 

Publish :

<apex:page standardController="LMS__c" >
<script>
var SAMPLEMC = "{!$MessageChannel.MsgVariable__c}";
    function handleClick() {
     var str=  document.getElementById('{!$Component.form1.comm}').value;
        const payload = {
            VariableName:str
        }
        sforce.one.publish(SAMPLEMC, payload);
      }
    </script>
    <apex:form id="form1" >
    <apex:inputText id="comm" value="{!str}" onchange="handleClick()"/>
    </apex:form>
</apex:page>

Subscribe : 

<apex:page standardController="LMS__c">
    <script>
    var subscriptionToMC;
    var MsgChannel = "{!$MessageChannel.MsgVariable__c}";
    window.onload=function subscribeM(){
    subscriptionToMC = sforce.one.subscribe(MsgChannel,function(message){
        //  alert(message.VariableName);
     document.getElementById("comm").innerHTML = message.VariableName;
    });
    }
    function unsubscribeMC() {
            if (subscriptionToMC) {
                sforce.one.unsubscribe(subscriptionToMC);
                subscriptionToMC = null;
            }
        }
    </script>
     <div id="comm"></div>
    <button onclick="unsubscribeMC()"> unsubscribe </button>
</apex:page>

Aura Component 

Publish : 

cmp

<aura:component implements="flexipage:availableForAllPageTypes">
    <lightning:messageChannel type="MsgVariable__c" aura:id="MsgChannelId" />
   Aura Publish : <lightning:input oninput="{!c.handleinput}"
onchange="{!c.handleinput}" type="text"/>
</aura:component>

JS

({
    handleinput : function(component, event, helper) {
        var str = event.getSource().get("v.value");
        var payload = {
            VariableName: str        
        };
        component.find("MsgChannelId").publish(payload);
    }
})

Subscribe :

cmp

<aura:component implements="flexipage:availableForAllPageTypes" >
    <aura:handler name="init" value="{!this}" action="{!c.handleChanged}"/>
    <aura:attribute name="recordValue" type="String"/>
    Aura Subscribe :<lightning:formattedText  value="{!v.recordValue}" />
    <lightning:messageChannel type="MsgVariable__c"
         onMessage="{!c.handleChanged}"/>
</aura:component>

JS 

({
    handleChanged : function(component, event, helper) {
            // Read the message argument to get the values in the message payload
           if (event != null && event.getParam("VariableName") != null) {
            component.set("v.recordValue", event.getParam("VariableName"));
           }
         }
})

LWC 

Publish : 

HTML

<template>
 <div style="border-style:groove;background-color:powderblue;">  
<lightning-input type="text" label="Publish lwc" onchange={handleOnChange}
oninput={handleOnChange}></lightning-input>
</div>
</template>

JS 

import { LightningElement ,wire} from 'lwc';
import {publish, MessageContext} from 'lightning/messageService';
import RECORD_SELECTED_CHANNEL from '@salesforce/messageChannel/MsgVariable__c';
export default class PublishLwc extends LightningElement {
@wire(MessageContext)
messageContext;
handleOnChange(event) {
    // Implement the logic to handle the selected file(s)
    const msg = event.target.value;
    console.log(msg);
    const payload ={VariableName:msg};
    publish(this.messageContext,RECORD_SELECTED_CHANNEL,payload);
    // Perform file processing or initiate upload to server
  }
}

Subscribe :

HTML

<template>
    <div style="border-style:groove;background-color:powderblue;">  
    subscribe lwc : {str}
    <lightning-button label="Unsubscribe" onclick={unsubscribeMC}></lightning-button>
    </div>

</template>

JS

import { LightningElement, api ,track,wire } from 'lwc';
import {unsubscribe,subscribe,MessageContext,APPLICATION_SCOPE}
from 'lightning/messageService';
import RECORD_SELECTED_CHANNEL from '@salesforce/messageChannel/MsgVariable__c';
export default class SubscribeLwc extends LightningElement {
    str ;
    subscription = null;
    @wire(MessageContext)
    messageContext;
    subscribeToMessageChannel(){
    if (!this.subscription) {
       this.subscription = subscribe(
       this.messageContext,RECORD_SELECTED_CHANNEL,(message) =>
{this.handleMessage(message)},{scope: APPLICATION_SCOPE}
       );
        }else{console.log('subscription is empty')}
       }
       handleMessage(message){
           console.log('inside handleMessage');
           this.str = message.VariableName;
           console.log(this.str);
       }    
       connectedCallback()
       {
           this.subscribeToMessageChannel();
       }
    unsubscribeMC() {
    unsubscribe( this.subscription);
    this.subscription = null;

    }

}


UI Screen Shot : 

As you can see below in the Message service1 tab I have mentioned value in Aura Publish and it reflects All the subscribe components also in below image you can see value is also added in another tab Message Service because I have mentioned Scope: Application_scope the LWC subscribe Component.  

Tab Message Service1


Tab Message Service




LWC  Note :

@wire(MessageContext) messageContext;

  •   The Lightning message service features automatically unregister when the component is destroyed.works with component life cycle

createMessageContext()

  •  If dont want to use @wire(MessageContext) adaptor then use createMessageContext() this will return messageContext

releaseMessageContext() 

  •  This will release the message context . releaseMessageContext(messageContext)   

  

Scope  (Application_Scope)

  • The Lightning message service lets you define the scope of where subscribing components receive messages in your application. 
  • You can limit the scope to the active area of the application or set the scope to the entire application.
  • For Lightning web components, the scoping feature is available only when using @wire(MessageContext).
  • The application's active area includes selected navigation tabs and items, utility items, and ES6 libraries. Utility items are always active.
  • inactive area example hidden console tabs.



If you have any Query/Feedback Mail me on shpu605@gmail.com (Priyanka Sharma). 

Comments