When we refresh the page (F5, or icon in browser), it will first trigger ONUNLOAD event. When we close the browser (X on right top icon),It will trigger ONUNLOAD event. Now
This is a huge hack with some limitations but it will work in most practical cases.
So if you just need something that works when users use the ctrl
+r
or cmd
+r
shortcut, you can keep track of whether r
is pressed when whatever you need to do upon reload/close gets run.
Simply create keydown
and keyup
event listeners that toggle a rDown
variable.
let rDown = false;
window.addEventListener("keydown", event => {
if (event.key == 'r')
rDown = true;
})
window.addEventListener("keyup", event => {
if (event.key == 'r')
rDown = false;
})
Then you have your "onunload" event listener where the listener function has an if
statement checking if rDown
is true
.
window.addEventListener("onunload", () => {
if (!rDown) {
// code that only gets run when the window is closed (or
// some psychopath reloads by actually clicking the icon)
}
});