当有人试图刷新页面时,我想检查一下。
例如,当我打开一个页面什么都没有发生,但当我刷新页面时,它应该显示一个警告。
当有人试图刷新页面时,我想检查一下。
例如,当我打开一个页面什么都没有发生,但当我刷新页面时,它应该显示一个警告。
当前回答
document.addEventListener("keydown", (e)=>{
if (e.keyCode === 116) {
e.preventDefault();
// your code here
// var r = confirm("Reload!");
// if (r == true)
// window.location.reload();
}
})
这里我们使用事件监听器“keydown”,因为F1 - F12键在浏览器上无法用于“keypress”。 116是“F5”的键码。检查在这里 'preventDefault()'将停止按下键的默认功能。 在这里,当按下F5时,它会停止直接刷新。 然后添加代码。 当警报被确认时,'location.reload()'将重新加载页面
其他回答
这里没有提到一个简单的解决方案(不依赖已弃用的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匹配,如果存储的时间与当前时间匹配(可能有一个微小的偏移),那么它是用户重新加载的页面。
在有人第一次访问该页面时存储一个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()">
下面是一个几乎所有浏览器都支持的方法:
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来检查页面是第一次打开还是刷新。
我写了这个函数来同时检查两个方法,使用旧的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:点击Reload按钮或使用Location.reload()
2:使用浏览器历史记录(Bakc和Forward)。
3:预渲染活动,如<link rel="prerender" href="//example.com/next-page.html">
4:任何其他方法。
<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>