Add event in LWC and Listen in Visualforce page
While reading this, you might have an idea how it should works and why ? In order to make it easy, I narrow down problem statement so I can write simple, short solution for future reference. All comments, ideas except spams are welcome.
In Aura app, ensure you define EVENT
In Visualforce page, add the listener to listen to the event. Ensure the event name is matched.
Problem Statement
- I have LWC which is embedded inside Aura and Aura is embedded inside Visualforce page. Why I come out with such design?
- Due to that I am not able to use the cool NavigationMixin for redirection
- Now how do I redirect page ?
Solution
Adding create event in LWC and add the listener to visualforce pageTechnical Implementation
In LWC javascript , create event on function that handles redirection. For example maybe you want user to go to different page when the button is clicked.
//function to redirect to opportunity detail handleOnOppLink(){ this.showLoadingSpinner = false; //create new Event with any meaningful name, in my case 'redirectFromLWC' this.dispatchEvent(new CustomEvent('redirectFromLWC', { detail: { recordId: this.opportunityId,recordMode:"detail"}, bubbles: true, composed: false, })); }
In Aura app, ensure you define EVENT
<aura:application access="GLOBAL" extends="ltng:outApp" > <aura:dependency resource="myCustom_lwc"/> <aura:dependency resource="markup://force:*" type="EVENT"/> </aura:application>
In Visualforce page, add the listener to listen to the event. Ensure the event name is matched.
<script> document.addEventListener("redirectFromLWC", function(event){ console.log('vf event data window listener => ', event.detail); //here is just code to get the details that passed from the event var detail =JSON.stringify(event.detail); console.log('data => '+detail); var data =JSON.parse(detail); console.log('data.recordId => '+data.recordId); var recordId =data.recordId; var recordMode =data.recordMode; //here the code is to handle navigation, as you can see I have to condition one in go to details // and another is go to edit. if(recordMode=='detail'){ if(recordId===''){ console.log('data.recordId 1=> '+ '{!oppId}'); recordId='{!CustomObject__c.Opportunity__c}'; } sforce.one.navigateToSObject(recordId, recordMode); } else if(recordMode=='edit'){ sforce.one.editRecord(recordId); } }); //other code </script>
Hi, trying to follow along and having difficulty. Can you show how and where you call handleOnOppLink() - is it on VF page somewhere? For example, do you just use a button with onclick="redirectFromLWC" ?? Thanks!
ReplyDeleteHello, Thank you for posting this blog.
ReplyDeleteI want to ask you how could assign the value of event.detail to Visualforce page's variables?