297

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
  • 1
    ha ha ha...Yes,that's quite right..but luckily it not my site...my client asking to do it on his side Commented Aug 16, 2011 at 15:03
  • 37
    Ya, but I am really happy to see those alerts when I am about to quit an unsaved Gmail page. Commented Nov 5, 2012 at 14:57
  • Note, on Firefox 4+ only a default message is displayed instead of your custom message developer.mozilla.org/en-US/docs/Web/Events/beforeunload#Notes Commented Oct 18, 2015 at 17:45
  • 5
    Possible duplicate of Warn user before leaving web page with unsaved changes Commented Jan 24, 2016 at 1:57

10 Answers 10

408

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.'); }); 
Sign up to request clarification or add additional context in comments.

15 Comments

@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
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.
@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/…
@RocketHazmat Chrome has, too. It now only says: Do you want to leave this site? Changes you made may not be saved.
@programmer5000 It's good because some malicious websites can show some useless warnings (for example "You can't leave without giving your bank information")
|
42

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 Comments

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.
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.
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
By the way... there's a better way here: stackoverflow.com/q/16322042/114029
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.
|
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; 

Comments

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> 

Comments

12

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 Comments

does this also fire if i refresh the page or just exit?
Yes, it will fire on a refresh or exit.
Is there anyway to know when it is refresh vs when its first time?
When a user comes to the page first time as oppose to the user refreshing the page.
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.
|
12

In order to have a popup 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 Comments

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

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
6

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?' } 

Comments

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

Comments

0

Just a bit more helpful, enable and disable

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.