Identifying Between Refresh And Close Browser Actions

前端 未结 13 1183
孤街浪徒
孤街浪徒 2020-11-22 15:29

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

13条回答
  •  粉色の甜心
    2020-11-22 15:44

    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)
        }
    });
    

提交回复
热议问题