如何在Javascript中区分第一个页面加载和连续的页面刷新事件

How to distinguish between the first page load and the consecutive page refresh events in Javascript?

本文关键字:连续 刷新 事件 加载 中区 Javascript 第一个      更新时间:2023-09-26

你好,我需要区分两个事件,

  1. 当页面第一次加载时,我想在标题中设置一些值,比如"Welcome"

  2. 以后,如果在加载后,如果用户刷新窗口,我希望我的Javascript检测到这是页面刷新事件,而不是错误的页面加载和设置一些其他值在头部说"你刚刚刷新了页面"

你能帮助实现这个吗?

正如这个答案所述,您可以使用cookie。当页面刷新时,该函数将检查cookie是否存在。如果没有,该函数将设置一个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标签中加入:

<body onload="checkFirstVisit()">

EDIT:要确保如果用户离开页面然后重新进入页面而不关闭和打开浏览器,您可以使用一些onunload事件来清除cookie

如果你不需要支持旧的浏览器,我建议使用localStorage:

if (localStorage.getItem("visit") == null)
{
    // Show Welcome message
    $('body').append("<h1>Welcome, guest!</h1>");
}
localStorage.setItem("visit", new Date());
// Here you can check if last visit date is longer than a day and clear it up, showing Welcome message again...

小提琴。

我可以使用Web Storage吗?