当有人试图刷新页面时,我想检查一下。

例如,当我打开一个页面什么都没有发生,但当我刷新页面时,它应该显示一个警告。


当前回答

这个实现帮助了我:

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

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

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

其他回答

<script>
    
    var currpage    = window.location.href;
    var lasturl     = sessionStorage.getItem("last_url");

    if(lasturl == null || lasturl.length === 0 || currpage !== lasturl ){
        sessionStorage.setItem("last_url", currpage);
        alert("New page loaded");
    }else{
        alert("Refreshed Page");  
    }

</script>

下面是一个几乎所有浏览器都支持的方法:

if (sessionStorage.getItem('reloaded') != null) {
    console.log('page was reloaded');
} else {
    console.log('page was not reloaded');
}

sessionStorage.setItem('reloaded', 'yes'); // could be anything

它使用SessionStorage来检查页面是第一次打开还是刷新。

这个实现帮助了我:

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

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

const isPageReload = navigationType === 'reload';
const isNavigation = navigationType === 'navigate';
const isBackForwarad = navigationType === 'back_forward';
const isPrerender = navigationType === 'prerender';
if(sessionStorage.reload) { 
   sessionStorage.reload = true;
   // optionnal
   setTimeout( () => { sessionStorage.setItem('reload', false) }, 2000);
} else {
   sessionStorage.setItem('reload', false);
}


我写了这个函数来同时检查两个方法,使用旧的window.performance.navigation和新的performance.getEntriesByType("navigation"):

function navigationType(){

    var result;
    var p;

    if (window.performance.navigation) {
        result=window.performance.navigation;
        if (result==255){result=4} // 4 is my invention!
    }

    if (window.performance.getEntriesByType("navigation")){
       p=window.performance.getEntriesByType("navigation")[0].type;

       if (p=='navigate'){result=0}
       if (p=='reload'){result=1}
       if (p=='back_forward'){result=2}
       if (p=='prerender'){result=3} //3 is my invention!
    }
    return result;
}

结果描述:

0:点击链接,在浏览器地址栏输入URL,提交表单,点击书签,通过脚本操作初始化。

1:点击Reload按钮或使用Location.reload()

2:使用浏览器历史记录(Bakc和Forward)。

3:预渲染活动,如<link rel="prerender" href="//example.com/next-page.html">

4:任何其他方法。