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

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


当前回答

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

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

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

sessionStorage.setItem("is_reloaded", true);

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

其他回答

if

event.currentTarget.performance.navigation.type

返回

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

这里没有提到一个简单的解决方案(不依赖已弃用的window.performance.navigation):

使用窗口。onbeforeunload在用户离开页面(可能会刷新页面)时存储当前页面的时间和URL(在localstorage中)。

window.onbeforeunload = function(e)
{
    localStorage.setItem('reload-url', window.location.href);
}

然后使用window。Onload从本地存储中获取这些值。

window.onload = function(e)
{
    if (localStorage.getItem('reload-url') != null)) 
    {
        if (window.location.href == localStorage.getItem('reload-url'))
        {
            console.log('Reload');
        }
    }
}

如果最近的URL与存储的URL匹配,如果存储的时间与当前时间匹配(可能有一个微小的偏移),那么它是用户重新加载的页面。

第一步是检查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.addEventListener("beforeunload", function(event) { 
     console.log("The page is redirecting")           
     debugger; 
});