Check if page gets reloaded or refreshed in JavaScript

前端 未结 12 3077
遇见更好的自我
遇见更好的自我 2020-11-21 22:57

I want to check when someone tries to refresh a page.

For example, when I open a page nothing happens but when I refresh the page it should display an alert.

12条回答
  •  深忆病人
    2020-11-21 23:23

    Here is a method that is supported by nearly all browsers:

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

    It uses SessionStorage to check if the page is opened the first time or if it is refreshed.

提交回复
热议问题