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

发布于 2024-10-18 01:21:10 字数 64 浏览 3 评论 0 原文

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

例如,当我打开页面时没有任何反应,但当我刷新页面时它应该显示警报。

I want to check when someone tries to refresh a page.

For example, when I open a page nothing happens but when I refresh the page it should display an alert.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(15

绳情 2024-10-25 01:21:10

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


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

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

来源:导航计时 API

⚠️⚠️⚠️ window.performance.navigation.type is deprecated. Please see Илья Зеленько's answer.


A better way to know that the page is actually reloaded is to use the navigator object that is supported by most modern browsers.

It uses the Navigation Timing 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");
}

Source: Navigation Timing API

骄兵必败 2024-10-25 01:21:10

2018 年至今的新标准 (PerformanceNavigationTiming)

window.performance.navigation 属性已弃用 /#obsolete" rel="noreferrer">导航计时级别 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 月 9 日支持

支持表

2023 年 7 月 19 日支持

支持表 2023-07-19

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

  • navigate - 通过单击链接、在浏览器地址栏中输入 URL、表单提交或通过脚本操作(而不是重新加载和初始化)进行初始化来启动导航。 back_forward 如下所列。

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

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

  • 预渲染 - 导航由预渲染提示<启动/a>.


该属性是只读的。

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

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

New standard 2018-now (PerformanceNavigationTiming)

window.performance.navigation property is deprecated in the Navigation Timing Level 2 specification. Please use the PerformanceNavigationTiming interface instead.

PerformanceNavigationTiming.type

This is an experimental technology.

Check the Browser compatibility table carefully before using this in production.

Check if page gets reloaded or refreshed in JavaScript

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

alert(pageAccessedByReload);

Support on 2021-11-09

Table of support

Support on 2023-07-19

Table of support 2023-07-19

The type read-only property returns a string representing the type of navigation. The value must be one of the following:

  • navigate — Navigation started by clicking a link, entering the URL in the browser's address bar, form submission, or initializing through a script operation other than reload and back_forward as listed below.

  • reload — Navigation is through the browser's reload operation or location.reload().

  • back_forward — Navigation is through the browser's history traversal operation.

  • prerender — Navigation is initiated by a prerender hint.

This property is Read only.

The following example illustrates this property's usage.

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);
  }
}
遮了一弯 2024-10-25 01:21:10

第一步是检查 sessionStorage 对于某些预定义值,如果存在,则提醒用户:

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

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

sessionStorage.setItem("is_reloaded", true);

会话值保留到页面关闭为止,因此,只有当页面在网站的新选项卡中重新加载时,它才会起作用。您还可以以同样的方式保留重新加载计数。

The first step is to check sessionStorage for some pre-defined value and if it exists, alert the user:

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

The second step is to set sessionStorage to some value (for example true):

sessionStorage.setItem("is_reloaded", true);

Session values kept until the page is closed, so it will work only if the page reloaded in a new tab with the site. You can also keep a reload count the same way.

独守阴晴ぅ圆缺 2024-10-25 01:21:10

当有人第一次访问该页面时存储 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 onload="checkFirstVisit()">

Store a cookie the first time someone visits the page. On refresh check if your cookie exists and if it does, alert.

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!');
  }
}

And in your body tag:

<body onload="checkFirstVisit()">
墟烟 2024-10-25 01:21:10

我编写了此函数来同时使用旧的 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: 单击“重新加载”按钮或使用 Location.reload()

2: 使用浏览器历史记录(后退和前进)。

3: 预渲染活动,例如

4:< /strong>任何其他方法。

I have written this function to check both methods using the old window.performance.navigation and the new performance.getEntriesByType("navigation") at the same time:

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;
}

Result description:

0: clicking a link, Entering the URL in the browser's address bar, form submission, Clicking bookmark, initializing through a script operation.

1: Clicking the Reload button or using Location.reload()

2: Working with browser history (Back and Forward).

3: prerendering activity like <link rel="prerender" href="//example.com/next-page.html">

4: any other method.

橘寄 2024-10-25 01:21:10

如果

event.currentTarget.performance.navigation.type

返回

0=>用户刚刚输入了一个 URL
1 =>页面已重新加载
2=>单击后退按钮。

If

event.currentTarget.performance.navigation.type

returns

0 => the user just typed in an URL
1 => the page reloaded
2 => the back button is clicked.

高速公鹿 2024-10-25 01:21:10

我在 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>

I found some information in 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>

梦里寻她 2024-10-25 01:21:10

这里有一个几乎所有浏览器都支持的方法:

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

Here is a method that is supported by nearly all browsers:

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

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

It uses SessionStorage to check if the page is opened the first time or if it is refreshed.

情释 2024-10-25 01:21:10

尚未提及一种简单的解决方案(不依赖于已弃用的 window.performance.navigation):

  1. 使用 window.onbeforeunload 来存储您的时间和 URL当用户离开页面(可能刷新页面)时当前页面(在本地存储中)。

    window.onbeforeunload = 函数(e)
    {
        localStorage.setItem('reload-url', window.location.href);
    }
    
  2. 然后使用window.onload从本地存储中获取这些值。

    window.onload = 函数(e)
    {
        if (localStorage.getItem('reload-url') != null))
        {
            if (window.location.href == localStorage.getItem('reload-url'))
            {
                console.log('重新加载');
            }
        }
    }
    
  3. 如果最近的 URL 与存储的 URL 匹配,并且存储的时间与当前时间匹配(可能有微小的偏移),则这是用户重新加载的页面。

One easy solution has not been mentioned (not relying on the deprecated window.performance.navigation):

  1. Use window.onbeforeunload to store the time and the URL of your current page (in localstorage) when the user leaves the page (potentially refreshes the page).

    window.onbeforeunload = function(e)
    {
        localStorage.setItem('reload-url', window.location.href);
    }
    
  2. Then use window.onload to get those values from localstorage.

    window.onload = function(e)
    {
        if (localStorage.getItem('reload-url') != null))
        {
            if (window.location.href == localStorage.getItem('reload-url'))
            {
                console.log('Reload');
            }
        }
    }
    
  3. If the recent URL matches the stored URL and if the stored time matches the current time (maybe with a tiny offset) then it is a page reload by the user.

幽蝶幻影 2024-10-25 01:21:10

这个实现帮助了我:

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

/** @var PerformanceNavigationTiming */
const navigationEntry = window.performance.getEntriesByType('navigation')[0];
const navigationType = navigationEntry.type;

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

This implementation helped me:

From MDN reference 2022: Navigation Timing Level 2 specification

/** @var PerformanceNavigationTiming */
const navigationEntry = window.performance.getEntriesByType('navigation')[0];
const navigationType = navigationEntry.type;

const isPageReload = navigationType === 'reload';
const isNavigation = navigationType === 'navigate';
const isBackForwarad = navigationType === 'back_forward';
const isPrerender = navigationType === 'prerender';
空心空情空意 2024-10-25 01:21:10

在 JavaScript 中(2023):

if (window.performance.getEntriesByType) {
    if (window.performance.getEntriesByType("navigation")[0].type === "reload") {
        alert("reloaded");
    }
}

In JavaScript (2023):

if (window.performance.getEntriesByType) {
    if (window.performance.getEntriesByType("navigation")[0].type === "reload") {
        alert("reloaded");
    }
}
韵柒 2024-10-25 01:21:10
if(sessionStorage.reload) { 
   sessionStorage.reload = true;
   // optionnal
   setTimeout( () => { sessionStorage.setItem('reload', false) }, 2000);
} else {
   sessionStorage.setItem('reload', false);
}


if(sessionStorage.reload) { 
   sessionStorage.reload = true;
   // optionnal
   setTimeout( () => { sessionStorage.setItem('reload', false) }, 2000);
} else {
   sessionStorage.setItem('reload', false);
}


无所的.畏惧 2024-10-25 01:21:10

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

window.addEventListener("beforeunload", function(event) {
     console.log("The page is redirecting")
     debugger;
});

Append the below script in the console:

window.addEventListener("beforeunload", function(event) {
     console.log("The page is redirecting")
     debugger;
});
爱已欠费 2024-10-25 01:21:10
<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>
<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>
温柔少女心 2024-10-25 01:21:10
 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()”将重新加载页面
 document.addEventListener("keydown", (e)=>{
   if (e.keyCode === 116) {
     e.preventDefault();

      // your code here
      // var r = confirm("Reload!");
      // if (r == true)
      //  window.location.reload();
   }
 })
  1. Here we used event listener 'keydown' because F1 - F12 keys are not available on browsers for 'keypress'.
  2. 116 is the keycode for 'F5'. Check here
  3. 'preventDefault()' will stop the default function of the key pressed.
    Here it stops direct refresh when F5 is pressed.
  4. Then add your code.
  5. When the alert is confirmed, 'location.reload()' will reload the page
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文