Check if page gets reloaded or refreshed in JavaScript

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

    ⚠️⚠️⚠️ window.performance.navigation.type is deprecated, pls see Илья Зеленько's answer


    A better way to know that the page is actually reloaded is to use the navigator object that is supported by most modern browsers.

    It uses the Navigation Timing API.

    //check for Navigation Timing API support
    if (window.performance) {
      console.info("window.performance works fine on this browser");
    }
    console.info(performance.navigation.type);
    if (performance.navigation.type == performance.navigation.TYPE_RELOAD) {
      console.info( "This page is reloaded" );
    } else {
      console.info( "This page is not reloaded");
    }

    source : https://developer.mozilla.org/en-US/docs/Web/API/Navigation_timing_API

提交回复
热议问题