Send Message from Lightning Out LWC to Visualforce

Send Message from Lightning Out LWC to Visualforce
Brett M. Nelson - Wednesday, October 14, 2020

Hello, I'm Brett with WIPDeveloper.com. Recently, I was working on a lightning web component that was being hosted in lightning out. And I was trying to use the lightning message service to communicate from the Lightning Web Component back to the Visualforce page. Apparently, lightning message service is not supported in that scenario. I ended up finding a workaround. Let's take a look at it. I have a lightning web component called LMS Test. It is going to have one method right now that's called when you click the button that select that method is going to be called send message. Send Message is going to send a custom event to a visual send message is going to send a custom event to the Visualforce page. question is how do we get the Visualforce page to know when to register to listen for the event. Let's first dispatch the event. So just so we know we're getting new, a new event each time, we're going to pass in the current date. So, this is what our event our event is going to be `hellofromlwc` and for the detail we're passing in the current date in the Visualforce page, once the component is registered, we're just using the normal LWC registration process here. Once the component is registered, we're going to add an event handler after creating the document for the component we're creating. So now, you might be wondering, since we're not applying a class to it, what we would query for, we can query directly for the element itself. So, sea bass LMS Test, then we can add our event listener. After the component is registered, we could use query selector to get the HTML tag c dash LMS best test. Once we have that we add the event listener, looking for Hello from LWC. And since we're passing the time, we're going to just log that to the dev console in the browser. So that is saved. Let's take a look in the browser. Now, I should be able to click the button and see the time in the console. There we go. We are successfully passing a message from a lightning web component that is hosted in lightning out on a Visualforce page back to the Visualforce page. The reason I was doing this was because there were limitations on using some of the built ins for the navigation mixin and the Visualforce page worked fine. So, this was my workaround around the navigation mix an issue which turned into looking for a workaround for the LMS not working with lightning out. So that's it for now. Remember to sign up for the weekly stand up and you can get all new information from WIPDeveloper.com