0

I have used window.onbeforeunload() to display an alert when the user navigates away from the page and this works fine,

  jQuery(window).bind('beforeunload', function (e) {
        var message = "Attention:";
        e.returnValue = message;
        return message;
    });

In one of the views in my project I have used a timer.The problem is that,when the timer is timed out an alert is displayed and it is followed by the window.onbeforeunload() alert.

I want only the timer alert and not both to be displayed on timer timeout.

How can I achieve this?

Sumedha Vangury
  • 643
  • 2
  • 17
  • 43

2 Answers2

0

As Shaunak commented, you should before unbind your "hardcoded" beforeunload function definition :

jQuery(window).unbind();

and then redefine it:

jQuery(window).bind('beforeunload', function (e) {
        var message = "Attention:";
        e.returnValue = message;
        return message;
    });
kiks73
  • 3,718
  • 3
  • 25
  • 52
0

to unbind an event, you need a reference to original handler.

please see below.

var func = function(e) {
  var message = "Attention:";
  e.returnValue = message;
  return message;
};

jQuery(window).bind('beforeunload', func);

// Unbind 'beforeunload' after 10 seconds
setTimeout(function() {
  jQuery(window).unbind('beforeunload', func);
  alert('beforeunload unbound');
}, 10000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Neverever
  • 15,890
  • 3
  • 32
  • 50