75

Does anyone know how to stop a page from reloading or navigating away?

jQuery(function($) {

    /* global on unload notification */
    warning = true;

    if(warning) {
        $(window).bind("unload", function() { 
            if (confirm("Do you want to leave this page") == true) {
                //they pressed OK
                alert('ok');
            } else {
                // they pressed Cancel
                alert('cancel');
                return false;
            }
        });
    }
});

I am working on an e-commerce site at the moment, the page that displays your future orders has the ability to alter the quantities of items ordered using +/- buttons. Changing the quantities this way this doesn't actually change the order itself, they have to press confirm and therefore committing a positive action to change the order.

However if they have changed the quantities and navigate away from the page I would like to warn them they are doing so in case this is an accident, as the changed quantities will be lost if they navigate away or refresh the page.

In the code above I am using a global variable which will be false by default (its only true for testing), when a quantity is changed I will update this variable to be true, and when they confirm the changes I will set it to false.

If warning is true and the page is unloaded, I offer them a confirmation box, if they say no they would like to stay on this page I need to stop it from unloading. return false isn't working, it still lets the user navigate away (the alerts are there for debugging only)

Any ideas?

Dan Atkinson
  • 11,391
  • 14
  • 81
  • 114
Natalie Downe
  • 3,036
  • 2
  • 20
  • 12

8 Answers8

87

onbeforeunload is the one you want; your function "should assign a string value to the returnValue property of the Event object and return the same string". Check the docs from Microsoft and Mozilla for details.

The string you return will be used by the browser to present the user with a custom confirm box, allowing them to refuse to stay there if they so choose. It has to be done that way to prevent malicious scripts causing a Denial-of-Browser attack.

NickFitz
  • 34,537
  • 8
  • 43
  • 40
  • 3
    It should be noted that if you're using jQuery to bind the event you should bind to `beforeunload` (leave off the `on` part of the string) – jgillman Sep 13 '12 at 22:11
  • This does not work anymore on modern browsers. You cannot put any custom message in the displayed box. (security reasons obviously) – mlwacosmos Oct 15 '19 at 08:13
72

This code warns as per Natalie's suggestion, but disables the warning if a form on the page was submitted. Uses JQuery.

var warning = true;
window.onbeforeunload = function() { 
  if (warning) {
    return "You have made changes on this page that you have not yet confirmed. If you navigate away from this page you will lose your unsaved changes";
  }
}

$('form').submit(function() {
   window.onbeforeunload = null;
});
mattmc3
  • 17,595
  • 7
  • 83
  • 103
crafter
  • 6,246
  • 1
  • 34
  • 46
  • 9
    Why the downvote? I answered and added to the topic. The warning variable is there to illustrate a proof of concept. Toggle it off or remove it. I'm sure most users won't copy code verbatim from this site and use it as is. – crafter Mar 27 '11 at 15:34
  • 8
    I'm guessing the downvote is because you set the warning variable and then don't use it in your submit function, e.g. just use `warning=false` rather than `window.onbeforeunload = null` – Bob Vale Mar 28 '12 at 17:29
  • 2
    The warning isn't needed in the event of a submit action...only if the user tries to leave the page WITHOUT submitting. – John Corry Aug 07 '14 at 15:30
21

you want to use the onbeforeunload event.

scunliffe
  • 62,582
  • 25
  • 126
  • 161
  • @scunliffe - in jQuery 'unload' means 'onbeforeunload', that's what she's doing. – karim79 Aug 19 '09 at 12:03
  • 17
    @karim79: no it doesn't. There isn't anything in jQuery that binds to the beforeunload function; "unload" binds to the "unload" event. Search the source if you don't believe me ;-) – NickFitz Aug 19 '09 at 12:24
6
window.onbeforeunload = confirmExit;
function confirmExit()
{
    return "You have attempted to leave this page.  If you have made any changes to the fields without clicking the Save button, your changes will be lost.  Are you sure you want to exit this page?";
}
Reto Koradi
  • 53,228
  • 8
  • 93
  • 133
VIKRANT SHARMA
  • 107
  • 2
  • 8
4
window.onbeforeunload = function() { 
  if (warning) {
    return `You have made changes on this page that you have not yet confirmed. 
    If you navigate away from this page you will lose your unsaved changes`;
  }
}

Isn't supported in chrome, safari and opera

Justin Liu
  • 581
  • 6
  • 21
1

As said in this comment, nothing in jQuery binds to the beforeunload event.

@karim79: no it doesn't. There isn't anything in jQuery that binds to the beforeunload function; "unload" binds to the "unload" event. Search the source if you don't believe me ;-) – NickFitz

So you have to use pure Javascript to bind a function to the beforeunload event.

var warning = true;
$("form").submit(function() {
  warning = false;
});
$('#exit').click(function() {
  window.location.replace('https://stacksnippets.net/js')
});
window.onbeforeunload = function() {
  if(warning) {
    return true;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<form>
<input type="submit">
</form>
Justin Liu
  • 581
  • 6
  • 21
0

Try this

    window.addEventListener('beforeunload', function (event) {
      event.preventDefault();

      event.returnValue = 'Are you sure you want to leave this page?';
    });
Mher
  • 985
  • 9
  • 23
-5

Try using e.preventDefault() instead of returning false. 'e' would be the first argument to your unload callback.

NSSec
  • 4,431
  • 1
  • 27
  • 29
  • @MathieuK - I voted up as I think you're right, but you should probably either 1)put in an example or 2)modify the code in the question to incorporate your suggestion before someone else comes along and does that ;) – karim79 Aug 19 '09 at 12:05
  • 16
    preventDefault won't have any effect on the unload event - it isn't possible for a script to cancel unload, as that would allow a malicious site to hijack the browser window. – NickFitz Aug 19 '09 at 12:49
  • preventdefault is not implemented on the unload event – Jens Meinecke Apr 09 '14 at 11:26