85

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

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
manraj82
  • 5,929
  • 24
  • 56
  • 83
  • 96
    Thank God the answer is no. – Vincent Ramdhanie Feb 09 '10 at 14:59
  • 8
    I don't want my window trying to force me to submit some form. Killing the process of the browser is a way you will not be able to prvent with javascript – Natrium Feb 09 '10 at 15:00
  • 5
    From a usability standpoint, what if the user doesn't want to fill out the form and leave/close the window for whatever reason? Won't that frustrate users on your site and drive them away? Or worse, enter in garbage data just to get the window to close? – John Lechowicz Feb 09 '10 at 15:02
  • 23
    Don't downvote because you find websites that do this distasteful. Provide a constructive alternative with the hope that he'll see the benefits of doing it some other way. The question is reasonable. – Jonathon Faust Feb 09 '10 at 15:04
  • That's just not how the web works - this *shouldn't* be possible. Your app sends some HTML and Javascript to the user and then it is out of your hands. JavaScript thankfully doesn't have THAT much control over the client. – FrustratedWithFormsDesigner Feb 09 '10 at 15:07
  • 1
    guys i really appreciate your comments,im 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 are designing.... – manraj82 Feb 09 '10 at 15:09
  • 3
    @manraj82: Many modern survey systems will be able to track the user's progress one page at a time. If the user aborts in the middle, they can resume just after the last stage they completed. – FrustratedWithFormsDesigner Feb 09 '10 at 15:15

8 Answers8

146

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

Community
  • 1
  • 1
Pool
  • 11,999
  • 14
  • 68
  • 78
  • 1
    This will not work in Opera, as it doesn't fire onbeforeunload events. – Marcel Korpel Feb 09 '10 at 20:42
  • 1
    Is opera a browser!!!! How can 1.6% people can use it! http://www.w3schools.com/browsers/browsers_stats.asp – Parixit Jul 02 '13 at 12:37
  • 11
    1.6% people that don't get annoyed by dialogs asking if they want to close a window? Seriously considering converting to Opera and becoming part of the now 1.603%.. – FrancescoMM Jul 04 '13 at 07:14
  • Firefox not showing any custom string message returned from confirmExit() function. – Nehal Jul 09 '13 at 09:23
  • 23
    @FrancescoMM There are all kinds of possible reasons that you might want to confirm that a user wants to close a page so they don't do it by accident. – jugg1es Mar 17 '15 at 19:10
  • 1
    MDN docs about this one at https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload – Stav Geffen Jun 04 '15 at 08:22
  • This doesn't work in firefox 59.0.2 and chrome 65.0.3325.181 now and how can I call a function when the page is closed? – gavinSong May 07 '18 at 06:57
  • There are some legitimate use for this. I am implementing an ethereum stream-base mentoring solution. If the user just close the window, he will lose money. – Loic Coenen Jan 20 '20 at 18:04
  • my legitimate use is we are allowing dispatchers to edit time card entries for the drivers and there is a ton of validation on that grid that is ran when the return button is clicked. Just closing the tab will make it possible to break financial settlement. I don't care about the ui aspect. Money trumps pretty. – John Lord Jul 06 '20 at 19:32
  • When unfinished to upload images, we need to tell the user not to close the tab. – DawnSong Dec 13 '20 at 03:29
  • 1
    Ahah [the only browser allowing for custom message](https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload#browser_compatibility) nowadays is IE! Geez, it's like the dude reaching for the party when everyone left. – Niki Romagnoli Apr 06 '21 at 08:37
16

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

TotPeRo
  • 6,561
  • 4
  • 47
  • 60
Imam
  • 179
  • 2
  • 4
11

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)

SQLMenace
  • 132,095
  • 25
  • 206
  • 225
  • 7
    First of all, of course this sort of "feature" should not be abused. There is always the possibility, that the action that needs to be confirmed/deferred is critical and/or time sensitive. For example, online banking. I submit a "billpay" transaction for a payment that needs to be initiated today. I am shown a review/confirmation page where I can `Edit`, `Confirm`, or `Cancel`. I switch to another browser tab and then inadvertently close the browser. I need the banking page to show and let me know that confirmation is required. Waiting until next week when I open billpay again is not ideal. – Kevin Fegan Nov 23 '16 at 04:03
7

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 = event || 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.

Julian Schmuckli
  • 3,681
  • 11
  • 37
  • 64
Gipsy King
  • 1,549
  • 9
  • 15
5

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);
}
Flimm
  • 136,138
  • 45
  • 251
  • 267
Aleksei
  • 145
  • 1
  • 8
4

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.

John Lechowicz
  • 2,573
  • 3
  • 21
  • 34
  • I'm pretty sure there are many pre-built survey systems that are already capable of this (not sure if they are a lot of $$, but that's another topic). – FrustratedWithFormsDesigner Feb 09 '10 at 15:41
  • we were actually depending on this prebuilt survey system,but it has proved to be useless...so was thinking of an easier way of doing it,but anyway thanks for your comments.... – manraj82 Feb 09 '10 at 16:33
1

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.

Jonathon Faust
  • 12,396
  • 4
  • 50
  • 63
0

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.

jpabluz
  • 1,200
  • 6
  • 16
  • 3
    then firefox is probably broken. They are the only one that isn't chromum - derived, and our code for our site (as well as the library we paid for that we use) is full of special code to fix stuff so that it displays correctly in firefox. Additionally I hope you didn't downvote this. This answer is ten years old and it probably worked then. – John Lord Jul 06 '20 at 19:36