291

I want to make a confirmation before user leaving the page. If he says ok then it would redirect to new page or cancel to leave. I tried to make it with onunload

<script type="text/javascript">
function con() {
    var answer = confirm("do you want to check our other products")
    if (answer){

        alert("bye");
    }
    else{
        window.location = "http://www.example.com";
    }
}
</script>
</head>

<body onunload="con();">
<h1 style="text-align:center">main page</h1>
</body>
</html>

But it confirm after page already closed? How to do it properly?

It would be even better if someone shows how to do it with jQuery?

4

10 Answers 10

405

onunload (or onbeforeunload) cannot redirect the user to another page. This is for security reasons.

If you want to show a prompt before the user leaves the page, use onbeforeunload:

window.onbeforeunload = function(){
  return 'Are you sure you want to leave?';
};

Or with jQuery:

$(window).bind('beforeunload', function(){
  return 'Are you sure you want to leave?';
});

This will just ask the user if they want to leave the page or not, you cannot redirect them if they select to stay on the page. If they select to leave, the browser will go where they told it to go.

You can use onunload to do stuff before the page is unloaded, but you cannot redirect from there (Chrome 14+ blocks alerts inside onunload):

window.onunload = function() {
    alert('Bye.');
}

Or with jQuery:

$(window).unload(function(){
  alert('Bye.');
});
15
  • 13
    @Joseph: When you return a string from onbeforeunload, the browser puts that string into its own confirmation box. Using confirm is useless in onunload and onbeforeunload, because only the browser can control where it goes, not you. Check out this demo: jsfiddle.net/3kvAC
    – gen_Eric
    Aug 16, 2011 at 15:10
  • 12
    Just a note, if you want to conditionally display a message in onbeforeunload, return false will make the browser show "false" in a dialog. You need to return undefined if you want to let the window close with no user alert.
    – Dan Fitch
    Apr 7, 2014 at 19:43
  • 7
    @Adam: Firefox decided to disallow customization of that message. That's part of the browser, so you cannot override that behavior. Other browsers may also be removing the ability to customize the message. See: developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/…
    – gen_Eric
    Aug 24, 2016 at 13:46
  • 11
    @RocketHazmat Chrome has, too. It now only says: Do you want to leave this site? Changes you made may not be saved.
    – user6560716
    Jan 25, 2017 at 18:47
  • 7
    @programmer5000 It's good because some malicious websites can show some useless warnings (for example "You can't leave without giving your bank information")
    – Naman
    Oct 29, 2017 at 15:39
41

This code when you also detect form state changed or not.

$('#form').data('serialize',$('#form').serialize()); // On load save form current state

$(window).bind('beforeunload', function(e){
    if($('#form').serialize()!=$('#form').data('serialize'))return true;
    else e=null; // i.e; if form state change show warning box, else don't show it.
});

You can Google JQuery Form Serialize function, this will collect all form inputs and save it in array. I guess this explain is enough :)

7
  • any idea why this would not work ? Could it be overwritten by other js functions/jquery plugins ? I'm running a webrtc app and I would like to "close" some stuff when the client closes the window thus the need to handle the window close.
    – hey
    Aug 8, 2014 at 4:02
  • 1
    this can be overwritten by any other plugin etc, mostly developer made mistake with selector, if you are doubted about overwritten, put your jquery code before close of </body> tag.
    – Wasim A.
    Aug 9, 2014 at 6:37
  • Yes... if you have some JS code that hides or disables input fields after the page has been loaded then when you do the check to compare the hidden\disabled fields won't be serialized. The check will fail of course. ;) There's this workaround: stackoverflow.com/a/4748748/114029 Oct 28, 2014 at 1:36
  • By the way... there's a better way here: stackoverflow.com/q/16322042/114029 Oct 28, 2014 at 2:01
  • 1
    should be noted that this will also rise a warning when pressing the submit button. one could serialize the form again on click of the submit button to prevent that.
    – Adam
    Sep 3, 2016 at 9:35
30

This what I did to show the confirmation message just when I have unsaved data

window.onbeforeunload = function() {
  if (isDirty) {
    return 'There is unsaved data.';
  }
  return undefined;
}

returning undefined will disable the confirmation

Note: returning null will not work with IE

Also you can use undefined to disable the confirmation

window.onbeforeunload = undefined;
22

This will alert on leaving current page

<script type='text/javascript'>
function goodbye(e) {
    if(!e) e = window.event;
    //e.cancelBubble is supported by IE - this will kill the bubbling process.
    e.cancelBubble = true;
    e.returnValue = 'You sure you want to leave?'; //This is displayed on the dialog

    //e.stopPropagation works in Firefox.
    if (e.stopPropagation) {
        e.stopPropagation();
        e.preventDefault();
    }
}
window.onbeforeunload=goodbye; 

</script>
12

In order to have a popop with Chrome 14+, you need to do the following :

jQuery(window).bind('beforeunload', function(){
    return 'my text';
});

The user will be asked if he want to stay or leave.

2
  • Any idea why this is not working ? I'm using chrome ( latest version) along with a bung of jquery plugins but I don't get any alert when when I close the window.
    – hey
    Aug 8, 2014 at 4:04
  • @hey Why the down vote ? It's working.... You need to make sure it's outside of the jQuery(document) and I suggest to put it right after all your plugins are loaded. Also, this snippet doesn't do any alert... it's only a demo with return. Aug 8, 2014 at 13:27
11

You can use the following one-liner to always ask the user before leaving the page.

window.onbeforeunload = s => "";

To ask the user when something on the page has been modified, see this answer.

7
  • does this also fire if i refresh the page or just exit?
    – Si8
    Jan 12, 2017 at 16:20
  • Yes, it will fire on a refresh or exit.
    – spencer.sm
    Jan 12, 2017 at 17:55
  • Is there anyway to know when it is refresh vs when its first time?
    – Si8
    Jan 13, 2017 at 0:00
  • When a user comes to the page first time as oppose to the user refreshing the page.
    – Si8
    Jan 13, 2017 at 14:19
  • Oh, no. It won't be fired when a user comes to the page for the first time. Only when closing or changing pages or refreshing.
    – spencer.sm
    Jan 13, 2017 at 15:53
8

Most of the solutions here did not work for me so I used the one found here

I also added a variable to allow the confirm box or not

window.hideWarning = false;
window.addEventListener('beforeunload', (event) => {
    if (!hideWarning) {
        event.preventDefault();
        event.returnValue = '';
    }

});
1
  • When user refresh the page browser refresh button this time Blocked attempt to show a 'beforeunload' confirmation panel for a frame that never had a user gesture since its load. this error occur any suggestion Mar 10, 2021 at 7:25
5

Normally you want to show this message, when the user has made changes in a form, but they are not saved.

Take this approach to show a message, only when the user has changed something

var form = $('#your-form'),
  original = form.serialize()

form.submit(function(){
  window.onbeforeunload = null
})

window.onbeforeunload = function(){
  if (form.serialize() != original)
    return 'Are you sure you want to leave?'
}
3
<!DOCTYPE html>
<html>
<body onbeforeunload="return myFunction()">

<p>Close this window, press F5 or click on the link below to invoke the onbeforeunload event.</p>

<a href="https://www.w3schools.com">Click here to go to w3schools.com</a>

<script>
function myFunction() {
    return "Write something clever here...";
}
</script>

</body>
</html>

https://www.w3schools.com/tags/ev_onbeforeunload.asp

0

Just a bit more helpful, enable and disable

$(window).on('beforeunload.myPluginName', false); // or use function() instead of false
$(window).off('beforeunload.myPluginName');

Not the answer you're looking for? Browse other questions tagged or ask your own question.