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>