Identifying Between Refresh And Close Browser Actions

前端 未结 13 1403
孤街浪徒
孤街浪徒 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 16:09

    Maybe someone is still searching for an answer...

    You can use SessionStorage for that! SessionStorage is not cleared when the page is reloaded but when it is closed. So basically you could set a key/value pair when the page is loaded, but before that you check if the key/value pair exists. If it does exists it means that the page was reloaded, if not it means that the user opened the page for the first time or in a new tab.

    if (sessionStorage.getItem('reloaded') != null) {
        console.log('page was reloaded');
    } else {
        console.log('page was not reloaded');
    }
    
    sessionStorage.setItem('reloaded', 'yes');
    

    This way you can doStuff() with the onunload event (user leaves the page), and otherStuff() if the key/value pair is set (user reloaded the page).

提交回复
热议问题