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

Ahm*_*med 158 javascript page-refresh

我想检查有人试图刷新页面的时间.

例如,当我打开页面时没有任何反应,但是当我刷新页面时会返回警报.

Rah*_*ain 203

知道页面实际重新加载的更好方法是使用大多数现代浏览器支持的导航器对象.

它使用Navigation Timing API.

//check for Navigation Timing API support
if (window.performance) {
  console.info("window.performance works fine on this browser");
}
  if (performance.navigation.type == 1) {
    console.info( "This page is reloaded" );
  } else {
    console.info( "This page is not reloaded");
  }
Run Code Online (Sandbox Code Playgroud)

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

  • `performance.navigation.type == performance.navigation.TYPE_RELOAD`更容易阅读,而不是`== 1`.另外,如果你检查`performance.navigation`,你会发现有4种不同的导航类型,如`TYPE_BACK_FORWARD`,`TYPE_NAVIGATE` (20认同)
  • 请注意.Chrome最近改变了这种行为.当用户单击当前地址栏并按Enter键时,performance.navigation.type的值将为1,该值应为0.我在版本56中进行了测试.不确定原因. (4认同)
  • wind️⚠️performance️`window.performance.navigation.type`已过时,请参见[我的回答](/sf/answers/3731531191/)。 (4认同)

Dit*_*Sky 39

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

if (sessionStorage.getItem("is_reloaded")) alert('Reloaded!');
Run Code Online (Sandbox Code Playgroud)

第二步是设置sessionStorage一些值(例如true):

sessionStorage.setItem("is_reloaded", true);
Run Code Online (Sandbox Code Playgroud)

会话值一直保持到页面关闭,因此仅当页面重新加载到包含该站点的新选项卡中时才会起作用.您也可以以相同的方式保持重新加载计数.

  • 有两点需要注意:1).您只能在会话和本地存储中存储字符串值.因此`true`被转换为'"true"`.2).会话存储一直持续到用户关闭浏览器窗口,因此您无法区分页面重新加载以及在同一浏览器会话中导航和返回到您的站点. (23认同)

Иль*_*ько 23

新标准2018,2019(PerformanceNavigationTiming)

window.performance.navigation属性在Navigation Timing Level 2规范中已弃用.请改用界面.PerformanceNavigationTiming

PerformanceNavigationTiming.type

这是一项实验技术.

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

支持于2014年11月14日:

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

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

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

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

  • 预渲染 - 导航由预渲染提示启动.

此属性为只读.

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

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);
  }
}
Run Code Online (Sandbox Code Playgroud)

  • +1 表示已弃用的 API,但 -100 表示苹果在 2020 年仍缺乏对 iOS 的支持 (16认同)
  • 感谢您指出了这一点。所以这是完全兼容的解决方案:https://jsfiddle.net/j9o1khcw/2/ (4认同)

tec*_*bar 14

第一次有人访问该页面时存储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!');
  }
}
Run Code Online (Sandbox Code Playgroud)

并在你的身体标签:

<body onload="checkFirstVisit()">
Run Code Online (Sandbox Code Playgroud)

  • 返回用户怎么样? (9认同)
  • 就像@ Rob2211所说,这只会检查页面是否已被访问过,并且只要在cookie还活着时重新访问该页面就会产生误报.不要用它来检查刷新. (5认同)
  • @Brannon - 是的,如果浏览器处于打开状态且用户在一段时间后重新访问,则不会将其视为新访问. (3认同)
  • @techfoobar 不错的收获。如果用户在 cookie 被销毁之前重新访问该网站,这是否仍然会造成问题? (2认同)

Ali*_*our 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;
}
Run Code Online (Sandbox Code Playgroud)

结果说明:

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

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

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

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

4:任何其他方法。


Vor*_*ato 6

我在这里找到了一些信息Javascript Detecting Page Refresh.他的第一个建议是使用隐藏字段,这些字段往往通过页面刷新来存储.

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
    }
}
Run Code Online (Sandbox Code Playgroud)
<html>

<body onLoad="JavaScript:checkRefresh();">
    <form name="refreshForm">
        <input type="hidden" name="visited" value="" />
    </form>

</body>

</html>
Run Code Online (Sandbox Code Playgroud)


nPc*_*omp 5

如果

event.currentTarget.performance.navigation.type
Run Code Online (Sandbox Code Playgroud)

回报

0 =>用户只需键入Url
1 =>页面重新加载
2 =>单击后退按钮.