Wednesday, July 2, 2008

Data Posting When the Winodw is Unloading?

I had a web application and it will do some data posting when it is closed. All the heavy lifting work in done in the onunload event handler for the page. However, it is not guaranteed that the data posting will be finished/succeed before the window is destroyed. So a Exit button is provided in the web application and the event handler to the button will do the heavy lifting work before calling
window.close();


We want to encourage users to click the Exit button instead of the browser closing button. So the design is that if users exit the application through browser closing button, a warning message will be thrown, and ask users if they really want to exit the application with the risk of losing data. If they choose ok, they will exit the application and probably the data will get lost. If they choose cancel, they will stay on the page.
window.onbeforeunload = confirmExit;

function confirmExit () {
if (!safeExit) {
return "You have attempted to leave the application without clicking the Exit button, and your progress will be lost. Are you sure you want to exit the application?";
}
}

//event handler for the Exit button
function doClickExit(){
safeExit = true;
//blahblah
}

Please see my previous post for more details about setting up the onbeforeunload event handler.

PS: I also tried synchronous XMLHttpRequest object for posting data, and it looks like it has a higher rate (maybe there is no data get lost forever) of posting data in the onunload event handler. But still, it is a good practice to provide a way which guarantees that data will be persisted and users are aware of it.

No comments: