0

I'm adding an event listener for onbeforeunload that prompts a confirmation message when the user tries to leave the page.

Unfortunately, I don't want the confirmation message to appear when the user tries to reload the page.

How do I do this?

Here's what I have so far:

window.onbeforeunload = function() {
    return "";
}
Spectric
  • 30,714
  • 6
  • 20
  • 43
shanks_9790
  • 73
  • 1
  • 6
  • `onbeforeunload` even runs before leaving the site, closing the tab, and refreshing the page. I don't think the browser distinguishes between them – evolutionxbox Jul 20 '21 at 15:03
  • https://stackoverflow.com/questions/568977/identifying-between-refresh-and-close-browser-actions may help – evolutionxbox Jul 20 '21 at 15:05
  • You may wanna look at this https://developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigationTiming/type And try to storage data, like timestamp in local storage for comparaison – Azoel Jul 20 '21 at 15:09

1 Answers1

0

It's completely possible1.

You can listen for the keydown event and check whether the user reloaded the page via the shortcut Ctrl + R. If so, you can set a variable (in our case, isReload) to true and set a timeout to set it back to false after, say, 100 milliseconds.

When the onbeforeunload event fires, check whether isReload is true. If it is, return null to allow the browser to close. Otherwise, return "" to prompt a confirmation.

Demo:

var isReload = false;
document.addEventListener('keydown', function(e){
    if(e.ctrlKey && e.keyCode == 82){
        isReload = true;
        setTimeout(function(){isReload = false}, 100);
    }
})
window.onbeforeunload = function(){
    if(!isReload){
        return "";
    }else{
        return null;
    }
}

1 This only works for the shortcut. You can't differentiate between closure/reload if the user manually clicks the reload button

Spectric
  • 30,714
  • 6
  • 20
  • 43