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.