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