How to Block Users from Closing a Window in JavaScript

How to block users from closing a window in Javascript?

Take a look at onBeforeUnload.

It wont force someone to stay but it will prompt them asking them whether they really want to leave, which is probably the best cross browser solution you can manage. (Similar to this site if you attempt to leave mid-answer.)

<script language="JavaScript">
window.onbeforeunload = confirmExit;
function confirmExit() {
return "You have attempted to leave this page. Are you sure?";
}
</script>

Edit: Most browsers no longer allow a custom message for onbeforeunload.

See this bug report from the 18th of February, 2016.

onbeforeunload dialogs are used for two things on the Modern Web:

  1. Preventing users from inadvertently losing data.
  2. Scamming users.

In an attempt to restrict their use for the latter while not stopping the former, we are going to not display the string provided by the webpage. Instead, we are going to use a generic string.

Firefox already does this[...]

How to block users to close the window in Oracle APEX builder

The reason this is not working is that unload event happens after the onbeforeunload event, so you're setting up the handler too late. If you execute the above JavaScript in the Page Load dynamic action, confirmExit will run when the user tries to close the window (or tab.)

Prevent user to close tab or browser window

Is that possible to start a loop on window.onbeforeunload to open same
current page again and again on tab exit?

Yes.

Why Its not possible?

but browser blocking it as popup opening

Your popup blocker is turned on at the browser you are testing the javascript at to prevent this browser behaviour by default; or by the setting that you have implemented.

Solution: Turn off the popup blocker at the browser that you are viewing https://jsfiddle.net/q9kd4b0x/ at .

A new window at a new tab should open at each onbeforeunload event

Prevent a user from closing a browser window using X?

Why do you want to do this? We can probably help you come up with a different design that doesn't require this if you tell us what you're trying to do.

However, to answer your question: it's not possible to catch that event in all cases. You cannot prevent the user from closing the browser or guarantee that your code will execute when they do. You can make it slightly annoying for them, but they can disable javascript, or kill the process, or reboot the computer. Using the unload function is the closest you can come to having some code that runs when the window closes (it will run in cases of normal shutdown or when the user navigates away).

How to prevent closing browser window?

Keep your code as is and use jQuery to handle links:

$(function () {
$("a").click(function {
window.onbeforeunload = null;
});
});


Related Topics



Leave a reply



Submit