Sometimes, we want to block users from closing a window in JavaScript.
In this article, we’ll look at how to block users from closing a window in JavaScript.
How to block users from closing a window in JavaScript?
To block users from closing a window in JavaScript, we can watch the beforeunload event.
For instance, we write
window.onbeforeunload = () => {
return "";
};
to set window.onbeforeunload to a function that’s called when the beforeunload event.
The beforeunload event is triggered when we close the window.
An alert box will show when we close the tab if we have an event listener for the beforeunload event.
Conclusion
To block users from closing a window in JavaScript, we can watch the beforeunload event.