How to block users from closing a window in Javascript?

JavascriptDom EventsAnti Patterns

Javascript Problem Overview


Is it possible to block users from closing the window using the exit button [X]? I am actually providing a close button in the page for the users to close the window.Basically what I'm trying to do is to force the users to fill the form and submit it. I don't want them to close the window till they have submitted it.

I really appreciate your comments, I'm not thinking of hosting on any commercial website. Its an internal thing, we are actually getting all the staff to participate in this survey we have designed....

I know its not the right way but I was wondering if there was a solution to the problem we have got here...

Javascript Solutions


Solution 1 - Javascript

Take a look at https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload">`onBeforeUnload`</a>;.

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[...]

Solution 2 - Javascript

If you don't want to display popup for all event you can add conditions like

window.onbeforeunload = confirmExit;
    function confirmExit() {
        if (isAnyTaskInProgress) {
           return "Some task is in progress. Are you sure, you want to close?";
        }
    }

This works fine for me

Solution 3 - Javascript

What will you do when a user hits ALT + F4 or closes it from Task Manager

Why don't you keep track if they did not complete it in a cookie or the DB and when they visit next time just bring the same screen back...:BTW..you haven't finished filling this form out..."

Of course if you were around before the dotcom bust you would remember porn storms, where if you closed 1 window 15 others would open..so yes there is code that will detect a window closing but if you hit ALT + F4 twice it will close the child and the parent (if it was a popup)

Solution 4 - Javascript

This will pop a dialog asking the user if he really wants to close or stay, with a message.

var message = "You have not filled out the form.";
window.onbeforeunload = function(event) {
	var e = e || window.event;
	if (e) {
        e.returnValue = message;
	}
	return message;
};

You can then unset it before the form gets submitted or something else with

window.onbeforeunload = null;

Keep in mind that this is extremely annoying. If you are trying to force your users to fill out a form that they don't want to fill out, then you will fail: they will find a way to close the window and never come back to your mean website.

Solution 5 - Javascript

If your sending out an internal survey that requires 100% participation from your company's employees, then a better route would be to just have the form keep track of the responders ID/Username/email etc. Every few days or so just send a nice little email reminder to those in your organization to complete the survey...you could probably even automate this.

Solution 6 - Javascript

How about that?

function internalHandler(e) {
    e.preventDefault(); // required in some browsers
    e.returnValue = ""; // required in some browsers
    return "Custom message to show to the user"; // only works in old browsers
}

if (window.addEventListener) {
    window.addEventListener('beforeunload', internalHandler, true);
} else if (window.attachEvent) {
    window.attachEvent('onbeforeunload', internalHandler);
}

Solution 7 - Javascript

It's poor practice to force the user to do something they don't necessarily want to do. You can't ever really prevent them from closing the browser.

You can achieve a similar effect, though, by making a div on your current web page to layer over top the rest of your controls so your form is the only thing accessible.

Solution 8 - Javascript

Well you can use the window.onclose event and return false in the event handler.

function closedWin() {
    confirm("close ?");
    return false; /* which will not allow to close the window */
}
if(window.addEventListener) {
     window.addEventListener("close", closedWin, false);
}

window.onclose = closedWin;

Code was taken from this site.

In the other hand, if they force the closing (by using task manager or something in those lines) you cannot do anything about it.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionmanraj82View Question on Stackoverflow
Solution 1 - JavascriptPoolView Answer on Stackoverflow
Solution 2 - JavascriptImamView Answer on Stackoverflow
Solution 3 - JavascriptSQLMenaceView Answer on Stackoverflow
Solution 4 - JavascriptGipsy KingView Answer on Stackoverflow
Solution 5 - JavascriptJohn LechowiczView Answer on Stackoverflow
Solution 6 - JavascriptAlekseiView Answer on Stackoverflow
Solution 7 - JavascriptJonathon FaustView Answer on Stackoverflow
Solution 8 - JavascriptjpabluzView Answer on Stackoverflow