10

I have a textarea that is submitted with ajax that uses onbeforeunload to warn the user that they have not submit the textarea if they try to close the browser. The problem is I need to somehow clear the onbeforeunload within the success of the ajax submit so that onbeforeunload knows that the user has submitted the form successfully. Is there a way to clear the onbeforeunload with a line of code, similar to a clearTimeout or clearInterval? I'll show the onbeforeunload code I currently have even though I don't think it matters much b/c I'm looking for a different function to clear this. No frameworks please. Thank you.

Function call

unsavedChangesWarning();

Onbeforeunload Function

function unsavedChangesWarning(){
    window.onbeforeunload = function(){
        return 'If you close this page you will lose your stride update!';
    };
}
Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
gmustudent
  • 2,229
  • 6
  • 31
  • 43

2 Answers2

25

window.onbeforeunload = null will clear it. Just add this before you try to redirect the user anywhere.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • According to https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload, "when this event returns (or sets the returnValue property to) a value other than null or undefined, the user is prompted to confirm the page unload." This is NOT true with FF 61 at least. I did the test to both return null and set e.returnValue to null, well the dialog still shows up. What really works is to hang up the listener like Niet the Dark Absol or danielson317 suggest. – Fabien Haddadi Jun 19 '18 at 09:40
1

For jQuery this looks like:

$(window).on('beforeunload', function (e)
{
  return 'Please dont leave me';
});

$(window).off('beforeunload');

I will actually be using the above solution to allow a clean refresh if the user session is expired. However for your use case I think it makes more sense to simply conditionalize the on before unload.

$('input, textarea, select').change(function()
{
  $(this).parents('form').addClass('dirty');
});
window.onbeforeunload = function()
{
  if ($('form.dirty').length)
  {
    var confirmationMessage = 'You have edited but not saved a form on this page.';

    (e || window.event).returnValue = confirmationMessage; //Gecko + IE
    return confirmationMessage; //Gecko + Webkit, Safari, Chrome etc.
  }
};
danielson317
  • 3,121
  • 3
  • 28
  • 43