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.

Problem Statement

  • Now how do I redirect page ?


Adding create event in LWC and add the listener to visualforce page

Technical 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
        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"/>

In Visualforce page, add the listener to listen to the event. Ensure the event name is matched.

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.
                console.log('data.recordId 1=> '+ '{!oppId}');
  , recordMode); 
         else if(recordMode=='edit'){

//other code


  1. Anonymous7/02/2020

    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!

  2. Hello, Thank you for posting this blog.

    I want to ask you how could assign the value of event.detail to Visualforce page's variables?


Post a Comment

Popular Posts