Categories
JavaScript Answers

How to block users from closing a window in JavaScript?

Spread the love

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.

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 *