Categories
JavaScript Answers

How to prompt user before browser close with JavaScript?

Spread the love

Sometimes, we want to prompt user before browser close with JavaScript.

In this article, we’ll look at how to prompt user before browser close with JavaScript.

How to prompt user before browser close with JavaScript?

To prompt user before browser close with JavaScript, we can return true in the beforeunload event handler.

For instance, we write:

window.onbeforeunload = (evt) => {
  return true;
}

to set the window.onbeforeunload property to a function that returns true to listen to the beforeunload event.

The beforeunload event is triggered right before we unload the page.

And since it returns true, we see a prompt before we close the browser tab.

Conclusion

To prompt user before browser close with JavaScript, we can return true in the beforeunload event handler.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *