How to handle browser close event in JavaScript?

To handle browser close event in JavaScript, add an event listener for beforeunload event.

Here's how you do it:

window.addEventListener('beforeunload', event => {
  event.returnValue = '';
});

This will trigger a popup asking the user something like:

// Leave site?
// Changes that you made may not be saved.