2

I have the following code

$(window).on('beforeunload', function()  
{  
  if(unsavedActionsExist)  
  {  
    return "changes will be lost. Do you want to proceed?";  
  }  
}

I get the confirm reload dialog box correctly. But my requirement is, if I click 'Reload' I need to do some 'actionA' & if I click 'Don't Reload' I need to do some 'actionB'. Please assist.

Sabitha
  • 273
  • 4
  • 14

1 Answers1

0

Following the strategies here, here and here, you can use the unload event to detect if the user leaves the page, and setTimeout to run a function if the user stays.

Note that the timeout gets set regardless of the user's choice, but the timer doesn't start until the "Confirm Reload" dialog is dismissed. To ensure the userStays() function doesn't execute if the user leaves, use a timeout interval that's longer than the expected time the $(window).on('unload') function will take.

var timeout;

var userStays = function() {
  // executed if the user stays 
  clearTimeout(timeout);
  $("#stayed").html("The user stayed.");
}

$(window).on('beforeunload', function() {
  $("#stayed").html("The user is leaving.");
  timeout = setTimeout(userStays, 200);
  return "Changes will be lost. Do you want to proceed?";
});


$(window).on('unload', function() {
  // executed if the user clicks "Reload this Page"
  console.log("Goodbye!");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="location.reload()">Reload</button>
<div id="stayed"></div>
Community
  • 1
  • 1
rphv
  • 5,409
  • 3
  • 29
  • 47
  • Just remember that End Task will prevent *any* of the code from executing and be aware that it's possible the script will never run. – zzzzBov Apr 21 '16 at 16:47