Sunday, 30 March 2014

window.onbeforeunload ajax request problem

From last few hours I was facing a problem with window.onbeforeunload. My need was to save form data(partial saving) by ajax, in case user opts to close the browser, reload the window or close the window. I was using following code :

//Old Code
window.onbeforeunload = function () {
  return msg;

It was saving my content but the return statement was showing me a confirmation message with options ‘Leave Page’ and ‘Stay on Page’. It was so embarrassing. Without return statement it was not saving my data at all.

After spending lot of time on internet and brainstorming a little found the following solution:

//New Code

$(window).bind('beforeunload', function () {
                //this will work only for Chrome

$(window).bind("unload", function () {
 //this will work for other browsers

It worked like a charm for me. Hopefully it will help someone else as well on internet.

Thanks!!!!! Enjoy Programming :)


Thanks for your valuable comments.