How can i prevent closure/refresh of a tab. I referred this link and yes we can execute logic on unload. But my requirement is to stop a user from navigating away, if the form is not saved.

I tried, native return message like: return 'Form is not saved!'; and, event.preventDefault() & event.stopPropogation(); // both doesn't seems to work.

Can anyone guide on how to accomplish this ? I am trying to acheive this is Community.

1 Answer 1


You can use the disconnetedCallback() of lwc, where you can display an alert message to user to confirm if the user want to really exit the page without saving. Another approach would be add an event listener to beforeunload() in constructor() that displays an alert message.

Please find the working code as below:

constructor() {
       window.addEventListener('beforeunload', (event) => {
  // Cancel the event as stated by the standard.
  // Chrome requires returnValue to be set.
  event.returnValue = 'sample value';

I have created a lwc component in my org and tested the above.


  • Thanks Mayank, Do you have a working code. I tried this as well, but it didn't worked for me. developer.salesforce.com/docs/component-library/tools/… Commented Jun 9, 2020 at 17:37
  • Thanks for the answer. It worked, event.returnValue did the trick ;) Commented Jun 10, 2020 at 14:22
  • This doesn't work for me, when my lwc is inside VF page
    – Patlatus
    Commented Sep 1, 2021 at 17:44
  • Can we prevent to back function, currently I am getting the popup message with cancel or continue Commented Nov 29, 2022 at 13:40

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .