jsLover
jsLover

Reputation: 1

Performing an action when a user decides to stay after onbeforeunload event

Here's my problem...

I want to preform an action once the user decides to stay. Since I don't have a direct way of doing so, I wanted to use the setTimeout and setInterval as following:

I'm using a setInterval to check the page every seconds, and if the isOnBeforeUnload var is true, it means the user triggered the onbeforeunload event by tying to leave.

What I want to happen is counting to 1 second, assuming after a second if the page is not unloaded yet - the user stayed.

window.onbeforeunload = function() {
                isOnBeforeUnload = true;
                return "You have an unsaved update!";
            };

window.timeout = setInterval(function() {

      if (isOnBeforeUnload) {
      var timeoutID = window.setTimeout(doClick, 1000);
      isOnBeforeUnload = false;
      }
   }, 1000);

function doClick() {
      //do some actions... 
      }

This code works fine on Chrome and IE, but not on FF... Can someone please help? I need it to work on IE9,10,11, Chrome and FF.

Thank you!

Upvotes: 0

Views: 1375

Answers (1)

Some Guy
Some Guy

Reputation: 16210

Here's a simpler solution:

window.onbeforeunload = function () {
  setTimeout(function () {
    console.log('Stayed');
    // The user stayed, so do whatever you want
  }, 100);
  return 'Dont go!';
};

Demo. It works in FF and Chrome. I can't test in IE, though.

Upvotes: 3

Related Questions