如何在JavaScript中区分首页加载事件和连续页面刷新事件? [英] How to distinguish between the first page load and the consecutive page refresh events in Javascript?

查看:93
本文介绍了如何在JavaScript中区分首页加载事件和连续页面刷新事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要区分2个事件,

  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 onload="checkFirstVisit()">

编辑:为确保用户离开页面然后重新进入页面而没有关闭和打开页面之间的浏览器,您可以使用一些onunload事件来清除cookie.

Hi I need to distinguish between 2 events,

  1. When the page loads for the first time, I want to set some value in the header say "Welcome"

  2. Later if after loading if the user refreshes the window, I would like my Javascript to detect this as page refresh event and not mistaken as page load and set some other value in the header say "You have just refreshed the page"

Can you help in implementing this?

解决方案

As this answer states, you can use cookies. When the page is refreshed, this function will check if the cookie exists or not. If it doesn't, the function will set a cookie. If the cookie does exist, then the function will alert "You refreshed!".

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

and in your body tag, put:

<body onload="checkFirstVisit()">

EDIT: To make sure that if a user leaves the page and then re-enters it without closing and opening the browser in between, you can use some onunload event to clear the cookie.

这篇关于如何在JavaScript中区分首页加载事件和连续页面刷新事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆