I'm using Lightning Message Channel to communicate between components on 2 different Pages and it's not working. The communication works when I put both these components on the same page.
Can someone please tell what's missing and why the communication is not working
Component that publishes to message channel
HTML
<template>
<lightning-card title="Publish - LWC">
<button type="button" onclick={publishMC}>Send Message</button>
</lightning-card>
</template>
js
import { LightningElement , api ,wire} from 'lwc';
import { MessageContext , createMessageContext, releaseMessageContext,publish } from 'lightning/messageService';
import SAMPLEMC from '@salesforce/messageChannel/TestMessageChannel__c'
export default class LMCPublish extends LightningElement {
acctInfo = {};
@wire(MessageContext)
context;
publishMC(){
acctInfo.Name = 'Test Name';
acctInfo.Phone = '9999999999';
const message = {
recordData: this.objAcctInfo
};
publish(this.context,SAMPLEMC,message);
}
}
Components the subscribes:
HTML
<template>
<lightning-card title="Subscribe LMC">
<button type="button" onclick={getMessage}>Get Message</button>
</lightning-card>
</template>
JS
import { LightningElement, wire } from 'lwc';
import { createMessageContext, releaseMessageContext, subscribe, unsubscribe ,APPLICATION_SCOPE} from 'lightning/messageService';
import SAMPLEMC from "@salesforce/messageChannel/TestMessageChannel__c";
export default class LMCSubscribe extends LightningElement {
objReceivedMessage = {};
@wire(MessageContext) messageContext ;
channel;
subscription = null;
receivedMessage;
getMessage(){
if (this.subscription) {
return;
}
this.subscription = subscribe(
this.messageContext,
SAMPLEMC, (message) => {
this.handleMessage(message);
},
{scope: APPLICATION_SCOPE});
}
handleMessage(message) {
console.log('message : ' ,message);
this.receivedMessage = message ? JSON.stringify(message, null, '\t') : 'no message payload';
console.log('this.receivedMessage : ',this.receivedMessage);
}
}
When placed on the same page, communication works perfectly. handleMessessage() method in subscriber is called and received message is displayed in console. However, when placed on different pages – handleMessage() method doesn't get called at all. What do you think is missing here?
Best Answer
LMS is for communication across DOM which means that it is for the component which is on the same tab but can be a VF in an iframe, or aura component. This is evident from the section When should I use LMS?
If you want to communicate between pages on different tabs, you will need to rely on
session storage
and events.