Check if page gets reloaded or refreshed in JavaScript

前端 未结 12 2867
遇见更好的自我
遇见更好的自我 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:38

    First step is to check sessionStorage for some pre-defined value and if it exists alert user:

    if (sessionStorage.getItem("is_reloaded")) alert('Reloaded!');
    

    Second step is to set sessionStorage to some value (for example true):

    sessionStorage.setItem("is_reloaded", true);
    

    Session values kept until page is closed so it will work only if page reloaded in a new tab with the site. You can also keep reload count the same way.

提交回复
热议问题