Search code examples
javascriptjqueryruby-on-railsgoogle-chrometurbolinks

In Rails, onbeforeunload not working consistently for Chrome browser


I'm trying to get onbeforeunload to work consistently on my page that has a form users are filling out. I'm expecting the following:

  • When I click a link to another page, it would prompt the user
  • When I refresh the page, it would prompt the user

I'm currently testing under Google Chrome, and I'm using the following now - though I've tried some variations.

<script>

  $(document).on('ready page:load', function () {
    $(window).on('beforeunload', function() {
      return "You should keep this page open.";
    });
  });

</script>

I've been able to get the prompt to show up at times but not consistently. I've thought this might point to a conflict with the code above and turbolinks. But haven't been able to find out a fix to get the expected results mentioned above.

--- Update:

Here's the code I eventually used.

<script data-turbolinks-eval="false">

$(document).ready(function() {
  form_modified=0;

  $('#report-form *').change(function(){
     form_modified=1;
  });

  $("#report-form input[name='commit']").click(function() {
      form_modified = 0;
  });
});

$(document).on('page:before-change', function() {

  if ($("#report-form").length > 0) {
    if (form_modified==1) {
      if (confirm("There are unsaved changes, click \"Cancel\" to remain on the page.")) {
        // clicks "OK", nothing here means
      } else {
        // clicks "Cancel"
        event.preventDefault();
      }
    }
  }
});

</script>

This method doesn't work for page refresh or exiting out by the window "X" however...


Solution

  • Turbolinks offers the page:before-change event for this kind of scenario.

    I'm however not sure why you bind your 2nd handler in your first handler. The window object doesn't change when you click on a Turbolinks link.