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

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


当前回答

在有人第一次访问该页面时存储一个cookie。刷新时检查你的cookie是否存在,如果存在,提醒。

function checkFirstVisit() {
  if(document.cookie.indexOf('mycookie')==-1) {
    // The cookie doesn't exist. Create it now
    document.cookie = 'mycookie=1';
  }
  else {
    // Not the first visit, so alert
    alert('You refreshed!');
  }
}

在你的body标签中:

<body onload="checkFirstVisit()">

其他回答

我在JavaScript检测页面刷新中找到了一些信息。他的第一个建议是使用隐藏字段,这些字段往往是通过页面刷新存储的。

function checkRefresh() { if (document.refreshForm.visited.value == "") { // This is a fresh page load document.refreshForm.visited.value = "1"; // You may want to add code here special for // fresh page loads } else { // This is a page refresh // Insert code here representing what to do on // a refresh } } <html> <body onLoad="JavaScript:checkRefresh();"> <form name="refreshForm"> <input type="hidden" name="visited" value="" /> </form> </body> </html>

在有人第一次访问该页面时存储一个cookie。刷新时检查你的cookie是否存在,如果存在,提醒。

function checkFirstVisit() {
  if(document.cookie.indexOf('mycookie')==-1) {
    // The cookie doesn't exist. Create it now
    document.cookie = 'mycookie=1';
  }
  else {
    // Not the first visit, so alert
    alert('You refreshed!');
  }
}

在你的body标签中:

<body onload="checkFirstVisit()">

第一步是检查sessionStorage是否有一些预定义的值,如果存在,提醒用户:

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

第二步是将sessionStorage设置为某个值(例如true):

sessionStorage.setItem("is_reloaded", true);

会话值保持,直到页面关闭,所以它将工作,只有当页面重新加载在一个新的标签与网站。你也可以用同样的方法保持重载计数。

这个实现帮助了我:

来自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';

⚠️⚠️⚠️window.performance.navigation.type已弃用。请看Илья Зеленько的回答。


了解页面是否实际被重新加载的更好方法是使用大多数现代浏览器支持的导航器对象。

它使用导航计时API。

//检查导航定时API支持 If (window.performance) { Console.info ("window.performance works fine on this browser"); } console.info (performance.navigation.type); 如果(performance.navigation。type == performance.navigation.TYPE_RELOAD) { console.info("此页面已重新加载"); }其他{ console.info("此页面未重新加载"); }

来源:导航定时API