Detect if page is load from back button

后端 未结 7 839
无人及你
无人及你 2021-02-06 23:07

Is there any way to detect if current page came from back button?

I want to load data from cookie only if current page came from back button.

7条回答
  •  不知归路
    2021-02-06 23:52

    For a simpler check, there're Navigation Timing API Spec (already deprecated, but widely supported) and Navigation Timing Level 2 API Spec (working draft, supported by major browser)

    if (window.performance) {
         var navEntries = window.performance.getEntriesByType('navigation');
         if (navEntries.length > 0 && navEntries[0].type === 'back_forward') {
              console.log('As per API lv2, this page is load from back/forward');
         } else if (window.performance.navigation
              && window.performance.navigation.type == window.performance.navigation.TYPE_BACK_FORWARD) {
              console.log('As per API lv1, this page is load from back/forward');
         } else {
              console.log('This is normal page load');
         }
    } else {
         console.log("Unfortunately, your browser doesn't support this API");
    }
    

提交回复
热议问题