views:

1049

answers:

3

Hello, I have a query regarding my application. Whenever user closes browser window accidentally I'd want to do some clean up operations before that. I have used onunload event but problem is this event is sometimes is firing and sometimes doesn't. What should I do, is there better way to handle such type of problem.

+1  A: 

From my experience onunload works differently in different browsers. Why dont you use another event handler called onbeforeunload instead. It should work. Onbeforeunload will execute first before the window closes, so that should solve your problem.

Saeros
A: 

Try:

window.unbeforeunload = function() { ...your code... }
ungarida
I tried to use onbefore unload event giving user an alert,but now the problem is i m getting two alerts one which i gave and other alert is given by browser.I just want my alert to fire.can u tell me how to get rid of this.
pradeep
On which browser?
ungarida
mozila?hw to get rid?i want this event to work in all browsers.
pradeep
I think it is all right, if before there is your alert then the browser alert. It's a matter of security you can not override browser business logic.
ungarida
Not tried, but make sure your function doesn't return anything at all.
Tilendor
+1  A: 
window.onbeforeunload = function() {
    return 'You have unsaved changes!';
}

See the MSDN article on onbeforeunload

Also there is a similar question in SO

rahul
I tried to use onbefore unload event giving user an alert,but now the problem is i m getting two alerts one which i gave and other alert is given by browser.I just want my alert to fire.can u tell me how to get rid of this.
pradeep
The link to the SO question might be helpful.
rahul