[SalesForce] How to handle standard toast events in LWC

For lightning I used a handler for force:showToast event to capture toasts for edit/new actions on standard pop up when a record was edited/inserted. I would like to do the same in lwc.

I added a listener in the constructor and it works well only for my custom toasts, but doesn't work for standard toasts when I open a standard pop up. Is there a way to capture standard toasts in lwc?

constructor() {
    super();
    document.addEventListener('lightning__showtoast', this.handleToastEvent.bind(this))
}

handleToastEvent (){
    console.log('toast')
}

Pop up is opened through NavigationMixin.Navigate

handleEditRecord(row) {
  this[NavigationMixin.Navigate]({
      type: 'standard__recordPage',
      attributes: {
          'recordId': row.Id,
          'actionName': 'edit'
      },
  })
}  

Best Answer

If you look at the documentation, to programmatically register your event listener you need to do the following in your "parent" LWC (an ancestor of the LWC generating the show toast event):

constructor() {
    super();

    this.template.addEventListener('lightning__showtoast', this.handleToastEvent.bind(this));
}

I tried this in a playground but the playground doesn't appear to correctly support toasts. It therefore looks like an exercise for the OP to see if this works.

I would assume you would need to provide a component that wraps all the others (perhaps via a "slot") in the page in order to catch "standard" toasts from these components, but I don't think you can catch toasts from the "chrome" of the page outside the body content.