如何使用js检查页面是否重新加载

问题描述 投票:0回答:3

现在如何检查页面是否重新加载?

以前是这样的:

//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");
}

但现在我发现导航类型已被弃用: https://developer.mozilla.org/en-US/docs/Web/API/Performance/navigation

然后我检查了替换:https://developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigationTiming

即使读完它,我仍然不太清楚如何实现这一目标。那么检查页面是否刷新的新方法是如何工作的呢?

我读完后也尝试过:

    if (PerformanceNavigationTiming.type == "reload") {
    alert('page reloaded')
    }

但是这样警报就不会显示了。

之后我尝试了这个:

    if (PerformanceNavigationTiming.type == PerformanceNavigationTiming.TYPE_RELOAD) {
    alert('page reloaded')
    }
    

但是随后它也会在不刷新页面的情况下显示警报。

然后我尝试的最后一件事:

  const pageAccessedByReload = (
      (PerformanceNavigationTiming && PerformanceNavigationTiming.TYPE === 1) ||
        window.performance
          .getEntriesByType('navigation')
          .map((nav) => nav.type)
          .includes('reload')
    );
    
    alert(pageAccessedByReload);

但这也给了我一个警告,要么在未重新加载时为假,要么在重新加载时为真。我只想在页面重新加载时发出警报。

javascript refresh
3个回答
5
投票

来自 MDN 参考 2022:导航计时级别 2 规范

const navigationType = 
    (window.performance.getEntriesByType('navigation')
        [0] as PerformanceNavigationTiming).type;

const isPageReload = navigationType === 'reload';
const isNavigation = navigationType === 'navigate';
const isBackForward = navigationType === 'back_forward';
const isPrerender = navigationType === 'prerender';

-1
投票

在阅读新的 API 文档时一定要记住,输入 PerformanceNavigationTiming 是一个字符串而不是数字,所以正确的方法是:

if (window.PerformanceNavigationTiming) {
  console.info("window.performance works fine on this browser");
  
  if (PerformanceNavigationTiming.type === "reload") {
    console.info("This page is reloaded");
  } else {
    console.info("This page is not reloaded");
  }
}


-1
投票

我终于找到解决办法了:

  const pageAccessedByReload = (
      (PerformanceNavigationTiming && PerformanceNavigationTiming.TYPE === 1) ||
        window.performance
          .getEntriesByType('navigation')
          .map((nav) => nav.type)
          .includes('reload')
    );
    
    if (pageAccessedByReload == true) {
    alert(pageAccessedByReload);
  }

现在只有刷新页面时才会显示。

© www.soinside.com 2019 - 2024. All rights reserved.