0

My javascript makes a jquery ajax call to the server to save the page fields. On the ajax success event I am invoking a window.location call to navigate to another webpage. The browser always displays a 'Leave site? Do you want to lose your changes' message when the navigation happens. I have tried various ways to suppress the message but they dont seem to work. I tried window.off syntax which failed

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

Then I went on to try the window eventlistener as below which again failed to suppress the alert

window.addEventListener("beforeunload", function (event) {
    event.preventDefault(); 
    event.returnValue = ''; 
});

Are there any other ways to suppress the leave site message. I am using Chrome version 75.x

Codecrasher99
  • 351
  • 3
  • 17
  • [prevent onbeforeunload to close page in any case](https://stackoverflow.com/questions/30781070/prevent-onbeforeunload-to-close-page-in-any-case). Hence, your issue is elsewhere – gaetanoM Jun 26 '19 at 13:55
  • @gaetanoM I may be misunderstanding but I don't see the relation. In fact, I believe they're opposites. That question is asking about how to restrict users from leaving, whereas this question is asking how to let them leave without a warning. – Tyler Roper Jun 26 '19 at 13:59
  • 2
    [Read the docs](https://api.jquery.com/off/): _"The `.off()` method removes event handlers that were attached with `.on()`."_ – Alon Eitan Jun 26 '19 at 14:00
  • 1. Why navigate to another page after saving fields using Ajax? Why not send the fields to a server process that saves them and redirects to the next page? 2. Somewhere in your page you have an onbeforeunload script you need to remove – mplungjan Jun 26 '19 at 14:10
  • @mplungjan I dont have any onbeforeunload script on my page. I even tried $(window).off('beforeunload'); but it doesnt work. As for sending the fields to a server process or middle tier well that would make the simple application a bit complicated. – Codecrasher99 Jun 27 '19 at 07:15
  • You cannot .off an event handler you did not .on as already mentioned – mplungjan Jun 27 '19 at 07:31
  • @mplungjan Instead of an ajax call I did a post operation to a handler and even that gives the same result. – Codecrasher99 Jun 27 '19 at 10:15

1 Answers1

1

Somewhere deep in my code there was a event listener for "beforeunload". Removing that eventlistener solved the problem.

Codecrasher99
  • 351
  • 3
  • 17