Lightning message service allows you to communicate between all UI technologies of Salesforce (LWC, Aura and Visualforce). This is the recommended way to communicate between lightning components and Visualforce.
Lighting message service communication works in below three steps
- Create a new
MessageChannel
metadata file and deploy to your org - Publish a message from one of the three UI technologies
- Subscribe to the message in any of the three UI technologies
1) Creating new MessageChannel
Currently Salesforce do not provide any option in the UI to create MessageChannel. So you have to deploy it as metadata.
isExposed
setting in metadata allow you to enable communicate between different namespaces/managed packages.
Copy below code metadata to messageChannels
folder in your code folder. Name the file as CarSelectionChannel.messageChannel-meta.xml
If you have sfdx installed, you can use below line to deploy the file.
sfdx force:source:deploy -p "pathToFile" -u targetOrgAliasHere
2) Publish event on the MessageChannel
This step varies depending on the whether you are publishing it from LWC or Aura or Visualforce. Our example scenario outlines subscribing and publishing from all three technologies.
3) Subscribing to events on MessageChannel
This step also varies depending on the whether you are publishing it from LWC or Aura or Visualforce. Our example scenario outlines subscribing and listening from all three technologies.
Visualforce Example
Here we use sforce.one
methods. This do not work as a stand alone visualforce page. Make sure you are inside lightning experience.
ie create a visualforce page with below code, create a tab for that visualforce page and check from lightning experience.
Aura Example
Here we use lightning:messageChannel
in the component to subscribe to event.
LWC Example
Here we import @salesforce/messageChannel/CarSelectionChannel__c
in JavaScript controller.
Also we use subscribe, unsubscribe methods imported from lightning/messageService
to subscribe to event.
Please note that if you are just publishing message to channel and not listening to it, you just need to import publish
method and the channel.
Then you can use the code in handleCarSelect
method to publish message to the channel.
Create app builder page to see the result in one page
In order to confirm that the event is getting published and received in all three technologies, put above visualforce, aura and lwc components in a new App builder page and add the page to any app. It should looks like the screenshot at starting of this post.