How to intercept page exit event with JavaScript?

Sometimes, we want to intercept page exit event with JavaScript.

In this article, we’ll look at how to intercept page exit event with JavaScript.

How to intercept page exit event with JavaScript?

To intercept page exit event with JavaScript, we listen for the beforeunload event.

For instance, we write

window.onbeforeunload = (e) => {
  //...
  return "Your confirmation message goes here.";
};

to set window.onbeforeunload to a function to add an event listener for the beforeunload event.

We return something non null in the function to show a message box when the user tries to exit the page.

The message in the box can’t be changed.

Conclusion

To intercept page exit event with JavaScript, we listen for the beforeunload event.