Subscribe, Unsubscribe MessageChannel in LWC, Aura and Visualforce Page in Salesforce

Subscribe, Unsubscribe MessageChannel in LWC, Aura and Visualforce Page in Salesforce

GitHub Source Code:

SampleChannel.messageChannel-meta.xml:

<?xml version=”1.0″ encoding=”UTF-8″?>
<LightningMessageChannel xmlns=”http://soap.sforce.com/2006/04/metadata”>
    <masterLabel>SampleChannel</masterLabel>
    <isExposed>true</isExposed>
    <description>This is a sample Lightning Message Channel.</description>
    <lightningMessageFields>
        <fieldName>variable1</fieldName>
        <description>Variable 1</description>
    </lightningMessageFields>
    <lightningMessageFields>
        <fieldName>variable2</fieldName>
        <description>Variable 2</description>
    </lightningMessageFields>
</LightningMessageChannel>


Aura:


Component:

<aura:component implements=”flexipage:availableForAllPageTypes” access=”global”>
   
    <aura:attribute type=”String” name=”ReceivedMessage”/>
   
    <lightning:messageChannel onMessage=”{!c.onMessageReceive}”
                              scope=”APPLICATION”
                              type=”SampleChannel__c”
                              aura:id=”sampleMessageChannel”/>
   
    <div class=”slds-box slds-theme–default”>
       
        <lightning:button label=”Publish” onclick=”{! c.publish }”/><br/><br/>
           
        Message Received is {! v.ReceivedMessage }
           
    </div>

</aura:component>


Component JavaScript:

({
   
    onMessageReceive : function( component, message, helper ) {
       
        if ( message != null )
            component.set( “v.ReceivedMessage”,
                          ( message.getParam( “variable1″ ) + ” – ” + message.getParam( “variable2” ) ) );

    },
   
    publish: function( component, event, helper ) {
        var payload = {
            variable1: “Sample”,
            variable2: “From Aura Component”
        };

        component.find( “sampleMessageChannel” ).publish( payload );
       
    }
   
})


LWC:

HTML:

<template>
    <lightning-card title=”Publishing from LWC” icon-name=”custom:custom14″>
        <div class=”slds-m-around_medium”>
            <lightning-button label=”Subscribe” onclick={subscribeMC}></lightning-button><br/><br/>
            <lightning-button label=”Unsubscribe” onclick={unsubscribeMC}></lightning-button><br/><br/>
            <lightning-button label=”Publish” onclick={handleClick}></lightning-button><br/><br/>
            Message Received is {receivedMessage}
        </div>
    </lightning-card>
</template>


JavaScript:

import { LightningElement, wire } from ‘lwc’;
import { subscribe, publish, MessageContext, APPLICATION_SCOPE } from ‘lightning/messageService’;
import SAMPLEMC from “@salesforce/messageChannel/SampleChannel__c”;

export default class MessageChannelLWC extends LightningElement {

    @wire(MessageContext)
    messageContext;
    receivedMessage;
    subscription = null;

    handleClick() {

        const message = {
            variable1: “Test”,
            variable2: “From LWC”
        };
        publish( this.messageContext, SAMPLEMC, message);

    }

    subscribeMC() {

        if (this.subscription) {
            return;
        }
        this.subscription = subscribe(
            this.messageContext,
            SAMPLEMC, ( message ) => {
                this.handleMessage( message );
            },
            {scope: APPLICATION_SCOPE});

    }

    unsubscribeMC() {

        unsubscribe( this.subscription );
        this.subscription = null;

    }

    handleMessage( message ) {

        this.receivedMessage = message ? JSON.stringify( message, null, ‘t’ ) : ‘no message payload’;

    }

}


JavaScript-meta.xml:

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


Visualforce Page:

<apex:page >
   
    <div>
       
        <p>Subscribe to SampleChannel</p>
        <button onclick=”subscribeMC()”>Subscribe</button>
        <p>Unsubscribe from SampleChannel</p>
        <button onclick=”unsubscribeMC()”>Unsubscribe</button>
        <br/>
        <br/>
        <button onclick=”publishMC()”>Publish</button>
        <br/>
        <br/>
        <p>Received message:</p>
        <textarea id=”MCMessageTextArea” rows=”10″ style=”disabled:true;resize:none;width:100%;”/>
       
    </div>
    <script>
   
        // Load the MessageChannel token in a variable
        var SAMPLEMC = “{!$MessageChannel.SampleChannel__c}”;
        var subscriptionToMC;
        // Display message in the textarea field
        function onMCPublished(message) {
           
            console.log( ‘Message is ‘ + JSON.stringify( message ) );
            var textArea = document.querySelector(“#MCMessageTextArea”);
            textArea.innerHTML = message ? JSON.stringify(message, null, ‘t’) : ‘no message payload’;
           
        }

        function subscribeMC() {
           
            if ( !subscriptionToMC ) {
               
                subscriptionToMC = sforce.one.subscribe( SAMPLEMC, onMCPublished, {scope: “APPLICATION”} );
                console.log( ‘Subscription is ‘ + JSON.stringify( subscriptionToMC ) );
               
            }
           
        }

        function unsubscribeMC() {
           
            if ( subscriptionToMC ) {
               
                sforce.one.unsubscribe( subscriptionToMC );
                subscriptionToMC = null;
               
            }
           
        }
   
        function publishMC() {
       
            const message = {
                variable1: “Example”,
                variable2: “From Visualforce Page”
            }
            sforce.one.publish( SAMPLEMC, message );
       
        }
   
    </script>

</apex:page>


Output:



Leave a Reply