22

I use this function to call on my window close.

This is the confirmation box popup window.

if(confirm("Sure you want to close the window");
{
     // yes return to submit function
}
else
{
  // no return to Other call function
}

window.onclose = function()
{
  alert('yes');
}

On Close of window on the top right corner with X symbol I need to return false. I am trying to use this window.onclose function but its not poping up.

Can anybody help me out?

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
user937194
  • 363
  • 3
  • 6
  • 12
  • 1
    Side note: Use [`console.log()`](http://stackoverflow.com/questions/4743730/what-is-console-log-and-how-do-i-use-it) instead of `alert()`. – Dom Apr 02 '13 at 16:42
  • 2
    Dom, how do you prevent the browser (Firefox in my case) to close the console when the window (or tab) is closed. console.log is useless, if you do not see the log because the console is closed together with the window... :-( – Peter Apr 06 '14 at 15:36
  • Peter, I know this is a bit old and I happen to be a different "Dom", but I know that chrome has a "preserve log" checkbox in its console. Firefox or firebug might have the same? – Dom Ramirez Dec 19 '14 at 21:01

2 Answers2

52

Unfortunately the popup window does not have any close event that you can listen to but there is a closed property that is true when window gets closed. A solution to get around this problem is to start a timer and check the closed property of the child window every second and clear the timer when the window gets closed. Here is the code:

var win = window.open('http://www.google.com','google','width=800,height=600,status=0,toolbar=0');   
var timer = setInterval(function() {   
    if(win.closed) {  
        clearInterval(timer);  
        alert('closed');  
    }  
}, 1000); 
Prakash Chennupati
  • 3,066
  • 3
  • 27
  • 38
30

There is no "close" event that you can catch with today's browsers.

There is an onbeforeunload but you can't do a lot when it is called, especially you can't prevent the window closing without the user consent and most distant operations will fail if you try them from the page which is being closed.

For a popup window, you can get the closing event, and do long operations, but only in the opener window :

 var w = window.open('popup.html');
 w.onbeforeunload = function(){
       // set warning message
 };

IMPORTANT: In recent versions of chrome, onbeforeunload only allows you to set the warning message; you may not run extra logic.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • 1
    You can stop the window from closing, but only with user intervention. I use this with an inline editor I made that tells you if you've got unsaved changes before leaving or closing the page.... `return "You have unsaved changes.";` – Reinstate Monica Cellio Apr 02 '13 at 16:55
  • 1
    @Archer right, my answer was too shortened. I edited to make it clearer. – Denys Séguret Apr 02 '13 at 16:56