Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear Onbeforeunload

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!';
    };
}
like image 939
gmustudent Avatar asked Dec 30 '12 19:12

gmustudent


People also ask

What triggers Onbeforeunload?

The beforeunload event is fired when the window, the document and its resources are about to be unloaded. The document is still visible and the event is still cancelable at this point. This event enables a web page to trigger a confirmation dialog asking the user if they really want to leave the page.

What is Onbeforeunload?

The onbeforeunload event occurs when the document is about to be unloaded. This event allows you to display a message in a confirmation dialog box to inform the user whether he/she wants to stay or leave the current page. The default message that appears in the confirmation box, is different in different browsers.

Can I use Onbeforeunload?

This feature is deprecated/obsolete and should not be used.


2 Answers

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

like image 61
Niet the Dark Absol Avatar answered Nov 06 '22 20:11

Niet the Dark Absol


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.
  }
};
like image 20
danielson317 Avatar answered Nov 06 '22 20:11

danielson317