Unable to unbind the window beforeunload event in Jquery
Asked Answered
B

2

16

I have a page where the user can drag and drop objects and save them as an image.When a user navigates away from the page, the event beforeunload is fired. Now, this happens every time. What i want to do is, unbind the event if the user has saved his work, so that the message may not pop up again.To do this i have used the unbind method in jQuery. But, it does not seem to work. Below is the code for binding and unbinding the events.

var notSaved = function()
{
   return 'You have not yet saved your work.Do you want to continue? Doing so, may cause loss of your work' ;
}
$(window).bind('beforeunload', notSaved);

After save method has been called,

$(window).unbind('beforeunload', notSaved);

What am i doing wrong here?
Also, the save method is actually an Ajax call.

Bussell answered 16/12, 2010 at 8:11 Comment(0)
X
36

beforeunload doesn't work reliably this way, as far as binding goes. You should assign it natively:

window.onbeforeunload = function() {
  return 'You have not yet saved your work.Do you want to continue? Doing so, may cause loss of your work' ;
}

And in your save method:

window.onbeforeunload = null;
Xylography answered 16/12, 2010 at 9:50 Comment(2)
Thank you so much...that saved the day for me :)Bussell
This won't work in IE, what you want is window.onbeforeunload = undefinedCataphoresis
I
0
const windowReloadBind = function(message) {
    window.onbeforeunload = function(event) {
        //--- Your logic
        return 'your output';
    }
};

const windowReloadUnBind = function() {
    window.onbeforeunload = function() {
      return null;
    };
};
Infanticide answered 18/11, 2019 at 4:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.