Send data from one Visualforce page to another using Lightning Message Service in Lightning
Yes! You heard me right. You can send data from one Visualforce page to another using Lightning Message Service in Visualforce pages too.
Yes! You heard me right you can use Lightning Message Service in Visualforce pages too. But there is a catch.
You can use LMS in Visualforce page only when the Visualforce page component is dragged and dropped on a record page.
There is a reason behind it. The JavaScript library sforce.one
is included in Visualforce only when it's embedded in Lightning like how I have mentioned above. You cannot use it in Salesforce Classic and you cannot use it when you try to iframe Visualforce page in an Aura Component.
Let's look at how to use LMS in Visualforce pages.
Here is the snippet!
<apex:page lightningStylesheets="true">
<apex:includeLightning />
<div id="lightning" />
<button onclick="handlePublish()">
Publish
</button>
<script>
//Get reference to the message channel
const GINFO = "{!$MessageChannel.LeadDataMessageChannel__c}"
function handlePublish() {
const payLoad = {
name: 'Teja'
}
//publish the data to Message Channel
sforce.one.publish(GINFO, payLoad);
console.log(GINFO);
}
</script>
</apex:page>
This is the Visualforce page that will subscribe to the message channel and starts receiving the data once it's pushed to message channel.
<apex:page lightningStylesheets="true">
<button onclick="handleSubscribe()">
Subscribe
</button>
<div class="receivedText">
</div>
<button onclick="handleUnsubscribe()">
Unsubscribe
</button>
<button onclick="clearData()">
Clear Data
</button>
<script>
//get reference to the message channel
const GINFO = "{!$MessageChannel.LeadDataMessageChannel__c}";
let subscription = null;
//function to handle subscribe functionality
function handleSubscribe() {
//check if the user is already subscribed
if (!subscription) {
//business logic is refactored to handleMessage
subscription = sforce.one.subscribe(GINFO, handleMessage);
}
}
//function to handle unsubscribe
function handleUnsubscribe() {
sforce.one.unsubscribe(subscription);
subscription = null;
}
function handleMessage(message) {
let receivedText = JSON.stringify(message, null, "\t");
document.querySelector('.receivedText').innerHTML = receivedText;
}
//function to clear the data
function clearData() {
document.querySelector('.receivedText').innerHTML = '';
}
</script>
</apex:page>
Hope this helps!