Salesforce introduced new sforce.one APIs — publish, subscribe, and unsubscribe — in Visualforce to interact with LMS.
The message channel reference is the first parameter to publish and subscribe. You can get this parameter from a new $MessageChannel Global variable within a {! } formula expression.
To publish on a Message Channel from a Visualforce page, include the $MessageChannel global variable in your page's JavaScript code and write a method that calls sforce.one.publish().
In the page's JavaScript, we first get a reference to the custom Lightning Message Channel with the formula expression {!$MessageChannel.SampleMessageChannel__c}. This expression creates a token that is unique to your Message Channel. We then assign the token as a string to the variable SAMPLEMC.
The function handleClick() contains the message content that we want to publish. Here, the message is a recordId with the value "some string" and recordData, whose value is the key-value pair value: "some value". We then call the Lightning Message Service API's publish() method on the sforce.one object. The publish() function takes two parameters, a string containing the Message Channel token and the message payload.
To subscribe and unsubscribe from a message channel, use the sforce.one.subscribe() and sforce.one.unsubscribe() methods.
Load the custom message channel $MessageChannel.SampleMessageChannel__c into the variable SAMPLEMC. The $MessageChannel global variable creates a unique token for the associated message channel. Under SAMPLEMC, we declare the variable subscriptionToMC that holds the subscription object returned from the sforce.one.subscribe() method.
The subscribeMC() method checks whether the subscription object is empty. If it is, then it calls the sforce.one.subscribe() method. sforce.one.subscribe() has two parameters, the subscribing message channel and onMCPublished(), the method that processes the message output. Similarly, the unsubscribeMC() method checks whether there is a subscription object. If so, it calls sforce.one.unsubscribe(), and passes in the subscriptionToMC object. Then, it clears the subscriptionToMC object.
The onMCPublished() method converts the message payload from a JSON object to a string. It then displays the message in the textarea with the ID MCMessageTextArea.
Get in touch with our expert Salesforce consultants to streamline your business processes and maximize efficiency.