Popup before window is closed

10,643

Solution 1

You can use the javascipt window.onunload or jquery unload method:

Javascript:

 window.onunload = function(){
 //Do something
 }

Jquery:

 $(window).unload(function(){
 //Do something
 });

Update: If the user has blocked pop-ups then you can not do anything. However you can use a confirm box instead of showing popup:

var r = confirm("Are you sure you want to leave?");

Solution 2

Simply this

window.onbeforeunload = function () {
     return 'Any string';
};
Share:
10,643
Ankush
Author by

Ankush

Updated on June 17, 2022

Comments

  • Ankush
    Ankush about 2 years

    I want to open a custom popup box when browser close button is pressed, I want to ask a question to the users exiting that why are they leaving my site. I have checked quite few posts but the best thing I found is something like this post

    http://stackoverflow.com/questions/10847156/jquery-dialog-box-before-closing-browser-window

    But this just opens a browser default confirm box. I want to open a custom box like colorbox. My page is http://cwstudio.in/browserclose/

    right now I am using alert function to open the popup but if I donot use the alert, the browser donot waits for my popup and just close it.

    Any help is appreciated.

    Thanks

  • Ankush
    Ankush about 11 years
    I am using $(document).ready(function(e) { $("#button").colorbox(); });
  • Ankush
    Ankush about 11 years
    and then $(window).unload(function(){ $("#button").click(); ` });`
  • Ankush
    Ankush about 11 years
    so this is suppose to open the popup in colorbox but it doesnot wait for it until I use alert
  • Milind Anantwar
    Milind Anantwar about 11 years
    If browser have settings to block the pop ups.the ball is not in ur court then
  • Ankush
    Ankush about 11 years
    I need to show 8 options, is it possible in confirm box in anyway?
  • Ankush
    Ankush about 11 years
    the popup blocker should block window.open or it will block the colorbox popup too?
  • Milind Anantwar
    Milind Anantwar about 11 years
    try using return false at the end of above functions.i am not sure but it should work.
  • Milind Anantwar
    Milind Anantwar about 11 years
    so its not possible. You can give confirm box.and if user clicks ok then try showing a div with return falls after it.