243

我想检查何时有人尝试刷新页面。

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

4

13 回答 13

256

⚠️⚠️⚠️window.performance.navigation.type已弃用,请参阅Илья Зеленько的答案


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

它使用导航计时 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");
}

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

于 2016-04-06T07:20:38.637 回答
77

2018 年至今的新标准(PerformanceNavigationTiming)

window.performance.navigation导航计时级别 2规范中已弃用该属性。请改用界面。PerformanceNavigationTiming

PerformanceNavigationTiming.type

这是一项实验技术

在生产中使用它之前,请仔细检查浏览器兼容性表。

检查页面是否在 JavaScript 中重新加载或刷新

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

alert(pageAccessedByReload);

2021-11-09 支持

支持表

type 只读属性返回一个表示导航类型的字符串。该值必须是以下之一:

  • 导航- 通过单击链接、在浏览器的地址栏中输入 URL、提交表单或通过除 reload 和 back_forward 之外的脚本操作进行初始化来启动导航,如下所列。

  • reload — 导航是通过浏览器的重新加载操作或location.reload().

  • back_forward — 导航是通过浏览器的历史遍历操作。

  • prerender — 导航由预渲染提示启动。

此属性是只读的。

以下示例说明了此属性的用法。

function print_nav_timing_data() {
  // Use getEntriesByType() to just get the "navigation" events
  var perfEntries = performance.getEntriesByType("navigation");

  for (var i=0; i < perfEntries.length; i++) {
    console.log("= Navigation entry[" + i + "]");
    var p = perfEntries[i];
    // dom Properties
    console.log("DOM content loaded = " + (p.domContentLoadedEventEnd - p.domContentLoadedEventStart));
    console.log("DOM complete = " + p.domComplete);
    console.log("DOM interactive = " + p.interactive);
 
    // document load and unload time
    console.log("document load = " + (p.loadEventEnd - p.loadEventStart));
    console.log("document unload = " + (p.unloadEventEnd - p.unloadEventStart));
    
    // other properties
    console.log("type = " + p.type);
    console.log("redirectCount = " + p.redirectCount);
  }
}
于 2018-11-14T19:35:40.797 回答
41

第一步是检查sessionStorage一些预定义的值,如果它存在警报用户:

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

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

sessionStorage.setItem("is_reloaded", true);

会话值一直保留到页面关闭,因此只有在页面重新加载到站点的新选项卡中时才会起作用。您也可以以相同的方式保持重新加载计数。

于 2013-07-25T10:22:26.817 回答
16

在有人第一次访问该页面时存储一个 cookie。刷新时检查您的 cookie 是否存在,如果存在,则发出警报。

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

在你的身体标签中:

<body onload="checkFirstVisit()">
于 2011-12-20T07:25:23.497 回答
14

我编写了这个函数来同时检查使用新旧两种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:点击链接,在浏览器地址栏输入网址,提交表单,点击书签,通过脚本操作进行初始化。

1:单击重新加载按钮或使用Location.reload()

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

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

4:任何其他方法。

于 2019-03-10T11:38:30.547 回答
7

I found some information here Javascript Detecting Page Refresh . His first recommendation is using hidden fields, which tend to be stored through page refreshes.

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>

于 2011-02-15T14:43:31.560 回答
7

如果

event.currentTarget.performance.navigation.type

返回

0 => 用户刚刚输入了一个 URL
1 => 页面重新加载
2 => 点击了返回按钮。

于 2017-02-02T21:56:55.060 回答
4

我在这里找到了一些信息 Javascript Detecting Page Refresh

function UnLoadWindow() {
    return 'We strongly recommends NOT closing this window yet.'
}

window.onbeforeunload = UnLoadWindow;
于 2017-02-01T07:48:07.833 回答
2

这是几乎所有浏览器都支持的方法:

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来检查页面是第一次打开还是刷新。

于 2020-08-18T23:14:08.173 回答
1
if(sessionStorage.reload) { 
   sessionStorage.reload = true;
   // optionnal
   setTimeout( () => { sessionStorage.setItem('reload', false) }, 2000);
} else {
   sessionStorage.setItem('reload', false);
}


于 2020-01-02T10:53:53.943 回答
1

在控制台中附加以下脚本:

window.addEventListener("beforeunload", function(event) { 
     console.log("The page is redirecting")           
     debugger; 
});
于 2020-11-18T06:35:44.917 回答
0
<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>
于 2020-10-12T15:15:41.533 回答
-1
 document.addEventListener("keydown", (e)=>{
   if (e.keyCode === 116) {
     e.preventDefault();

      // your code here
      // var r = confirm("Reload!");
      // if (r == true)
      //  window.location.reload();
   }
 })
  1. 在这里,我们使用了事件监听器“keydown”,因为 F1 - F12 键在浏览器上不能用于“keypress”。
  2. 116 是“F5”的键码。在这里检查
  3. 'preventDefault()' 将停止按键的默认功能。当按下 F5 时,它会停止直接刷新。
  4. 然后添加您的代码。
  5. 确认警报后,'location.reload()' 将重新加载页面
于 2021-07-24T06:09:18.487 回答