Click here to Skip to main content
15,890,982 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi, I have created a program in IE.
OnBeforeUnload or OnBeforeClose code is used to close database connection and update a few things.
The code for these never finishes fully when the user hits the X button of the browser.
Unless i place an Alert(""); then it will not finish executing the code.

Does anyone know a way around this? I have been stuck on this for so long and cant find any help anywhere.:confused:

Thanks
Posted
Comments
Sandeep Mewara 12-Oct-10 9:21am    
OnBeforeUnload or OnBeforeClose code of what? Any control?
[no name] 12-Oct-10 11:38am    
body

1 solution

I think the best possible way would be to check if the user changed anything. If so then store this and confirm that the user really wants to exit the page. Something like:

JavaScript
function beforeClose(){
    if(inputChanged){
        // ... save data here
        return 'Are you sure you want to navigate away?';
    }
}


Above also looks kind of user friendly. I also was thinking about something else but I haven't tested this. The idea is to setup a timer and return false and let the timer event handle the saving and closing of the page. You probably will need a global variable to keep track if saving is already done, otherwise closing will never work.

var isSaved = false;

<body onbeforeunload="if (!isSaved) {setTimeout('handleWindowClose();',50);return false;}">

function handleWindowClose()
{
  // Save data
  isSaved = true;
  // Close window
}



Good luck!
 
Share this answer
 
Comments
Dalek Dave 12-Oct-10 9:42am    
Good Answer.
[no name] 12-Oct-10 11:19am    
Thanks - trying it now.
[no name] 12-Oct-10 11:39am    
Hey can you include how to do this without any 'Alert' popping up? if i use your 2nd method, although it seemed like it would work, it gives an Alert.
I need it to not have an alert saying 'are you sure you wish to leave' or whatever.
E.F. Nijboer 13-Oct-10 11:03am    
Maybe the second post (by Katty) could help you out: http://forums.techarena.in/software-development/1183627.htm
Another thing you could try is window.onbeforeunload = null; instead of isSaved = true; but I haven't tested this and doubt if it actually will work. I guess the message is mandatory and didn't find anything that could prevent the message. As you already tried the code won't execute completely otherwise. But maybe the popup solution does the trick.
[no name] 13-Oct-10 11:09am    
Ok, thanks - accepted.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900