sm是什么意思| 小朋友口臭是什么原因| balea是什么牌子| 什么是童子命| 想什么来什么是什么定律| 单核细胞百分比偏高什么原因| 长一根白眉毛预示什么| 回本是什么意思| 顺产1-3天吃什么好| 肚子经常胀气是什么原因| 人到无求品自高什么意思| 准生证有什么用| 毛毛虫吃什么食物| 因地制宜是什么意思| 女性什么时候绝经| 狗狗什么时候打疫苗| 云南白药气雾剂保险液有什么作用| 吃什么药可以流产不用去医院| 互攻是什么意思| 农村适合养殖什么| 虫草能治什么病| 湿疹是长什么样的| 顺风顺水是什么生肖| 什么是数位| 小白鼠吃什么| 脱肛吃什么药最有效| 胎方位loa是什么意思| 抑郁症挂什么科室| gm是什么牌子| 酒糟鼻子是什么原因引起的| 李子为什么不能多吃| 囊肿是什么病严重吗| pray是什么意思| 中暑什么感觉| 4级手术是什么意思| 部长是什么级别| 南是什么结构| 二元酸是什么| p是什么意思啊| 小孩腰疼是什么原因| 酸菜吃多了有什么危害| 恶寒什么意思| 鼻尖痒是什么原因| 梦到被蛇咬是什么意思周公解梦| 大学挂科是什么意思| 三个代表代表了什么| 啪啪啪是什么意思| 老鼠疮是什么病| 子宫肌腺症是什么病| 马齿苋是什么| 什么药能降肌酐| 太原有什么特产| 甲状腺过氧化物酶抗体高说明什么问题| 牙肿了吃什么消炎药| 伽蓝菩萨保佑什么| 马眼是什么意思| 手机越狱什么意思| 看结石挂什么科室| 眼袋是什么原因造成的| 为什么一躺下就头晕目眩| 肚子疼做什么检查| 什么水果补血| 门当是什么| 10万个为什么| 什么食物清肺化痰| 桂枝和肉桂有什么区别| 刻舟求剑什么意思| 经常干咳嗽是什么原因| 印记是什么意思| 宝宝消化不良吃什么药| 长白毛是什么原因| 吃榴莲补什么| 有什么别有病| 长方形的纸可以折什么| 7月24是什么星座| 肝实质密度减低是什么意思| 苹果6和苹果6S有什么区别| 什么时候需要做肠镜| 海的尽头是什么| 月经稀发是什么意思| 月经血量少是什么原因| 10月9日什么星座| 氢键是什么| 慢性心肌炎有什么症状| En什么意思| 工会经费是什么| 纪梵希为什么不娶赫本| 来月经头晕是什么原因| 烧裆是什么原因| 眉毛中间叫什么部位| 大连机场叫什么| 舌苔很白是什么原因| 猫睡在枕头旁说明什么| 一天当中什么时候血压最高| 高筋小麦粉适合做什么| 吃什么吐什么| 廓清是什么意思| 飞机票号是什么意思| 肚脐下方疼是什么原因| 怀孕吐得厉害吃什么可以缓解| 无住生心是什么意思| 每天放屁多是什么原因| 尿味道很重是什么原因| 宫颈囊肿有什么症状表现| 鸡蛋炒什么| 龟头是什么| 甘油脂肪酸酯是什么| 白细胞低吃什么药可以增加白细胞| 大仙为什么知道你的事| 大便次数少是什么原因| 阴茎中途疲软吃什么药| 血稠是什么原因造成的| 维c之王是什么水果| 什么药吃了死的快| 垂爱是什么意思| 皮肤黏膜是什么| 吃东西没有味道是什么原因| 三摩地是什么意思| 女性长期便秘挂什么科| 北阳台适合种什么植物| 硬不起来吃什么药| 手心脚心热吃什么药| 211属于什么大学| 痔疮吃什么药好的快| 苋菜不能和什么一起吃| 什么是买手店| 支那人是什么意思| 嗔恨是什么意思| 又热又冷是什么原因| tdi是什么意思| 腰椎挂什么科室| 儿童看牙齿挂什么科| 寄居蟹吃什么| 尿结石挂什么科| 饭后烧心是什么原因引起的| 白雪什么什么| 摩纳哥为什么这么富| 什么是低筋面粉| 小孩血糖高有什么症状| 为什么不建议做冠脉cta检查| 1129什么星座| 龟奴是什么| 物色什么意思| 阿僧只劫是什么意思| 鸽子补什么| 教学相长什么意思| 粉色裤子配什么上衣好看| 金融行业五行属什么| 掌中宝是什么部位| 精神洁癖是什么意思| 怕冷的女人是什么原因| 70年产权是从什么时候开始算| 为什么排卵期会出血| 细菌性前列腺炎有什么症状| 4ever是什么意思| 钠低会出现什么症状| 内痔用什么药治最好效果最快| 打乒乓球有什么好处| 金鱼藻是什么植物| 研究员是什么级别| 阿莫西林吃多了有什么副作用| 花旦是什么意思| 处女膜是什么样的| 肩周炎吃什么药好得快| 腿有淤青是什么原因| 羟基丁酸在淘宝叫什么| 醋加小苏打有什么作用| 一起共勉是什么意思| 指甲上有白点是什么原因| 白开水喝多了有什么危害| 维生素b是什么食物| 澳门什么时候回归| 不什么不什么的四字词语| 眼睛感染用什么眼药水| 耳鸣是什么原因引起的| 灵芝孢子粉有什么作用| xo兑什么饮料好喝| 白发多吃什么可以改善| 故步自封是什么意思| 分开后我会笑着说是什么歌| 辛弃疾字什么| ft什么意思| soie是什么面料| 唐朝为什么灭亡| 朋友圈发女朋友照片配什么文字| 例假为什么第一天最疼| 欲钱看正月初一是什么生肖| 怜悯之心是什么意思| 化疗后白细胞低吃什么补得快| 质粒是什么| 什么情况会导致月经推迟不来| 黑猫警长叫什么名字| 江与河有什么区别| 有龙则灵的灵是什么意思| 子宫颈肥大有什么危害| 什么是公因数| 下午一点到三点是什么时辰| 六味地黄丸治什么| 干咳嗽喉咙痒是什么原因| 公元前3000年是什么朝代| 手刃是什么意思| 离婚要什么手续| 左肋骨下方是什么器官| 豆浆和什么不能一起吃| 聿五行属什么| 五经指什么| 什么是平年| 爽字代表什么生肖| 布洛芬缓释胶囊是什么药| 腻歪是什么意思| 分解酒精的是什么酶| 湿疹可以吃什么| 亚健康是什么意思| 取保候审是什么意思还会判刑吗| 水金龟属于什么茶| 曹休和曹操什么关系| 梅干菜是什么菜做成的| 跳蚤是什么样的图片| 肠胃不好吃什么菜比较好| 逆商是什么意思| 脑供血不足吃什么| 为什么经常放屁| 思想感情是什么意思| 治脚气用什么药| 拉肚子喝什么饮料| 负罪感什么意思| 为什么脚底板发黄| 间接胆红素偏高什么意思| 狗狗体内驱虫用什么药最好| 低血糖要吃什么| 煮牛肉放什么调料| 膀胱湿热吃什么中成药| 黑色的蜜蜂是什么蜂| 什么是溶血性疾病| 出水痘不能吃什么食物| 尿道感染用什么药| 最后一个出场叫什么| 哪里是什么意思| 结节是什么原因引起的| 什么床不能睡觉| 大侠是什么意思| 感冒了吃什么水果好| 右肩膀疼是什么原因| 什么地游泳| 万中无一什么意思| 动物奶油是什么做的| 激光脱毛挂什么科| 女生小便带血是什么原因| 为什么说秦始皇还活着| 顺手牵羊是什么生肖| 外阴病变有什么症状| 做tct检查前要注意什么| 钢铁侠叫什么名字| 3月10日是什么星座| n2是什么意思| 什么血型好| 排卵期出血是什么原因造成的| 晚上12点是什么时辰| 张卫健属什么生肖| 摸摸头是什么意思| dumpling是什么意思| 迷津是什么意思| 滴度是什么意思| 茹毛饮血什么意思| 百度
Table of Contents
Step 1: We’ve gotta store the last reload time
Step 2: We need a way to handle and store the reload count
Step 3: “Dear user, why you didn’t listen?!”
Bonus: Let’s re-Vue it!
Wrapping up
Home Web Front-end CSS Tutorial One Way to Break Users Out of the Habit of Reloading Too Much

Apr 13, 2025 am 11:25 AM

百度 一时间,各类糖果企业也带着自己的展品出现在了糖酒会的现场。

One Way to Break Users Out of the Habit of Reloading Too Much

Page reloads are a thing. Sometimes we refresh a page when we think it’s unresponsive, or believe that new content is available. Sometimes we’re just mad at the dang site and rage-refresh to let it know we’re displeased.

Wouldn’t be nice to know when a user refreshes the page? Not just that, but how many times? That data can help us trigger some sort of behavior after a certain number of reloads.

A sports site is a good example. If I want to check the score of a game that’s in progress but the scores aren’t live-updated, then I might find myself refreshing a bunch.

Our goal is to break users out of that habit. We’ll use our page-refresh-counting powers to let folks know that refreshes are unnecessary, thanks to real-time score updates. And if they reload more than three times? We’ll kick ‘em out of their session. That’ll show them.

Here’s a simple demo of that concept.

Let’s re-create it together. But before we get going, there are few questions we need to answer before we start coding:

  • How can we persist the number of times user reloaded the site? We need a place to keep the number of times user reloaded the site (reloadCount), this place needs to persist that value between the reloads — localStorage sounds like a good solution.
  • How do we detect if user reloaded the site or just came back after few hours? If we store the reloadCount in localStorage it will persist the value between the reloads, but it will keep that value until we remove programmatically or clear the browser storage. It means that if we come back after few hours the site will still remember last reloadCount and may perform logout after first refresh without warning. We want to avoid that and allow user to reload the site two times each time the user comes back after some period of time. That last sentence holds the answer to the question. We need to store the time when the user left the site and then when the site loads again check when that happened. If that time period wasn’t long enough, we activate the reload counting logic.
  • How do we know when the user leaves the site? To store that time, we use beforeunload window event and store that value in localStorage.

OK, now that we have the answers, let’s dive into the code.

Step 1: We’ve gotta store the last reload time

We will store the time of last reload using a beforeunload window event. We need two things: (1) an event listener that will listen to the event and fire the appropriate method, and (2) our beforeUnloadHandler method.

First, let’s create a function called initializeReloadCount that will set our event listener using the addEventListener method on the window object.

function initializeReloadCount() {
  window.addEventListener("beforeunload", beforeUnloadHandler)
}

Then we create a second method that will be fired before we leave the site. This method will save the time the refresh happens in localStorage.

function beforeUnloadHandler() {
  localStorage.setItem("lastUnloadAt", Math.floor(Date.now() / 1000))
  window.removeEventListener("beforeunload", beforeUnloadHandler);
}

Step 2: We need a way to handle and store the reload count

Now that we have the time when the site was last closed, we can proceed and implement logic that’s responsible for detecting and counting how many times the site was reloaded. We need a variable to hold our reloadCount and tell us how many times user reloaded the site.

let reloadCount = null

Then, in our initializeReloadCount function, we need to do two things:

  1. Check if we already have a reloadCount value stored in our localStorage, and if so, get that value and save it in our reloadCount. If the value doesn’t exist, it means that the user loaded the site for the first time (or at least did not reload it). In that case, we set the reloadCount to zero and save that value to localStorage.
  2. Detect if the site was reloaded or the user came back to the site after longer period of time. This is the place where we need our lastUnloadAt value. To detect if the site was actually reloaded, we need to compare the time when the site gets loaded (the current time) with the lastUnloadAt value. If those two happened within, say, five seconds (which is totally arbitrary), that means the user reloaded the site and we should run reload count logic. If the time period between those two events is longer, we reset the reloadCount value.

With that, let’s create a new function called checkReload and keep that logic there.

function checkReload() {
  if (localStorage.getItem("reloadCount")) {
    reloadCount = parseInt(localStorage.getItem("reloadCount"))
  } else {
    reloadCount = 0
    localStorage.setItem("reloadCount", reloadCount)
  }
  if (
    Math.floor(Date.now() / 1000) - localStorage.getItem("lastUnloadAt") 
<p>The last function we need in this step is a method responsible for what happens when we confirm that the user reloaded the site. We call that function onReloadDetected, and inside it, we increment the value of reloadCount. If the user refreshed the site third time, we drop the bomb and call our logout logic.</p>
<pre rel="JavaScript">function onReloadDetected() {
  reloadCount = reloadCount   1
  localStorage.setItem("reloadCount", reloadCount)
  if (reloadCount === 3) {
    logout()
  }
}

Step 3: “Dear user, why you didn’t listen?!”

In this step, we implement the logic responsible for the situation when the user reloads the site to the point of breaching our three-limit threshold, despite our clear warnings to stop doing it.

When that happens, we call our API to log the user out, then we clean up all properties related to the reload count logic. That will allow the user to come back and have a clean account of reloads. We can also redirect the user somewhere useful, like the login screen. (But wouldn’t it be funny to send them here instead?)

function logout(params) {
  // logout API call
  resetReloadCount()
}

function resetReloadCount() {
  window.removeEventListener("beforeunload", beforeUnloadHandler)
  localStorage.removeItem("lastUnloadAt")
  localStorage.removeItem("reloadCount");
}

Bonus: Let’s re-Vue it!

Now that we have the logic implemented, let’s see how can move that logic to a Vue site based on this example:

First, we need to move all of our variables into our component’s data, which is where all reactive props live.

export default {
  data() {
    return {
      reloadCount: 0,
      warningMessages: [...]
    }
  },

Then we move all our functions to methods.

// ...
  methods: {
    beforeUnloadHandler() {...},
    checkReload() {...},
    logout() {...},
    onReloadDetected() {...},
    resetReloadCount() {...},
    initializeReloadCount() {...}
  }
// ...

Since we are using Vue and its reactivity system, we can drop all direct DOM manipulations (e.g. document.getElementById("app").innerHTML) and depend on our warningMessages data property. To display the proper warning message we need to add a computed property that will re-calculate each time our reloadCount is changed so that we can return a string from our warningMessages.

computed: {
  warningMessage() {
    return this.warningMessages[this.reloadCount];
  }
},

Then we can access our computed property directly in the component’s template.

<template>
  <div>
    <p>{{ warningMessage }}</p>
  </div>
</template>

Last thing we need to do is find a proper place to activate the reload prevention logic. Vue comes with component lifecycle hooks that are exactly what we need, specifically the created hook. Let’s drop that in.

// ...
  created() {
    this.initializeReloadCount();
  },
// ...

Nice.

Wrapping up

And there it is, the logic that checks and counts how many times a page has been refreshed. I hope you enjoyed the ride and you find this solution useful or at least inspiring to do something better. ?

The above is the detailed content of One Way to Break Users Out of the Habit of Reloading Too Much. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
CSS tutorial for creating loading spinners and animations CSS tutorial for creating loading spinners and animations Jul 07, 2025 am 12:07 AM

There are three ways to create a CSS loading rotator: 1. Use the basic rotator of borders to achieve simple animation through HTML and CSS; 2. Use a custom rotator of multiple points to achieve the jump effect through different delay times; 3. Add a rotator in the button and switch classes through JavaScript to display the loading status. Each approach emphasizes the importance of design details such as color, size, accessibility and performance optimization to enhance the user experience.

Addressing CSS Browser Compatibility issues and prefixes Addressing CSS Browser Compatibility issues and prefixes Jul 07, 2025 am 01:44 AM

To deal with CSS browser compatibility and prefix issues, you need to understand the differences in browser support and use vendor prefixes reasonably. 1. Understand common problems such as Flexbox and Grid support, position:sticky invalid, and animation performance is different; 2. Check CanIuse confirmation feature support status; 3. Correctly use -webkit-, -moz-, -ms-, -o- and other manufacturer prefixes; 4. It is recommended to use Autoprefixer to automatically add prefixes; 5. Install PostCSS and configure browserslist to specify the target browser; 6. Automatically handle compatibility during construction; 7. Modernizr detection features can be used for old projects; 8. No need to pursue consistency of all browsers,

What is the difference between display: inline, display: block, and display: inline-block? What is the difference between display: inline, display: block, and display: inline-block? Jul 11, 2025 am 03:25 AM

Themaindifferencesbetweendisplay:inline,block,andinline-blockinHTML/CSSarelayoutbehavior,spaceusage,andstylingcontrol.1.Inlineelementsflowwithtext,don’tstartonnewlines,ignorewidth/height,andonlyapplyhorizontalpadding/margins—idealforinlinetextstyling

Styling visited links differently with CSS Styling visited links differently with CSS Jul 11, 2025 am 03:26 AM

Setting the style of links you have visited can improve the user experience, especially in content-intensive websites to help users navigate better. 1. Use CSS's: visited pseudo-class to define the style of the visited link, such as color changes; 2. Note that the browser only allows modification of some attributes due to privacy restrictions; 3. The color selection should be coordinated with the overall style to avoid abruptness; 4. The mobile terminal may not display this effect, and it is recommended to combine it with other visual prompts such as icon auxiliary logos.

Creating custom shapes with css clip-path Creating custom shapes with css clip-path Jul 09, 2025 am 01:29 AM

Use the clip-path attribute of CSS to crop elements into custom shapes, such as triangles, circular notches, polygons, etc., without relying on pictures or SVGs. Its advantages include: 1. Supports a variety of basic shapes such as circle, ellipse, polygon, etc.; 2. Responsive adjustment and adaptable to mobile terminals; 3. Easy to animation, and can be combined with hover or JavaScript to achieve dynamic effects; 4. It does not affect the layout flow, and only crops the display area. Common usages are such as circular clip-path:circle (50pxatcenter) and triangle clip-path:polygon (50%0%, 100 0%, 0 0%). Notice

What is the CSS Painting API? What is the CSS Painting API? Jul 04, 2025 am 02:16 AM

TheCSSPaintingAPIenablesdynamicimagegenerationinCSSusingJavaScript.1.DeveloperscreateaPaintWorkletclasswithapaint()method.2.TheyregisteritviaregisterPaint().3.ThecustompaintfunctionisthenusedinCSSpropertieslikebackground-image.Thisallowsfordynamicvis

How to create responsive images using CSS? How to create responsive images using CSS? Jul 15, 2025 am 01:10 AM

To create responsive images using CSS, it can be mainly achieved through the following methods: 1. Use max-width:100% and height:auto to allow the image to adapt to the container width while maintaining the proportion; 2. Use HTML's srcset and sizes attributes to intelligently load the image sources adapted to different screens; 3. Use object-fit and object-position to control image cropping and focus display. Together, these methods ensure that the images are presented clearly and beautifully on different devices.

What are common CSS browser inconsistencies? What are common CSS browser inconsistencies? Jul 26, 2025 am 07:04 AM

Different browsers have differences in CSS parsing, resulting in inconsistent display effects, mainly including the default style difference, box model calculation method, Flexbox and Grid layout support level, and inconsistent behavior of certain CSS attributes. 1. The default style processing is inconsistent. The solution is to use CSSReset or Normalize.css to unify the initial style; 2. The box model calculation method of the old version of IE is different. It is recommended to use box-sizing:border-box in a unified manner; 3. Flexbox and Grid perform differently in edge cases or in old versions. More tests and use Autoprefixer; 4. Some CSS attribute behaviors are inconsistent. CanIuse must be consulted and downgraded.

See all articles
夏威夷果吃了有什么好处 靛青色是什么颜色 脖子粗大是什么病的症状 万岁是什么意思 青春痘用什么药膏擦最好呢
尿检是检查什么的 大于90度的角是什么角 胸口疼是什么病的前兆 感冒吃什么药好得快 2月22是什么星座
ecco什么牌子 11月11日什么星座 梦见手指流血是什么预兆 mpa是什么单位 放疗有什么危害
艾司唑仑是什么药 肾亏是什么原因造成的 为什么说尽量不戴脚链 钢镚是什么意思 trans什么意思
胰腺炎为什么喝水就死hcv8jop8ns6r.cn 花千骨什么时候上映的hcv8jop5ns2r.cn 北戴河是什么海hcv7jop6ns8r.cn 屁多是什么病的前兆hcv8jop8ns7r.cn 梦见捡板栗是什么意思shenchushe.com
黑户是什么hcv9jop1ns0r.cn 煲什么汤含蛋白质高hcv7jop5ns0r.cn 巫山云雨是什么意思hcv7jop9ns4r.cn H 什么意思hcv8jop6ns0r.cn eicu是什么意思hcv8jop1ns2r.cn
太累吃什么缓解疲劳hcv8jop8ns2r.cn 减肥中午吃什么imcecn.com 最后一个出场叫什么hcv9jop6ns7r.cn 收敛是什么意思hcv9jop0ns4r.cn 女同叫什么hcv8jop5ns1r.cn
月经9天了还没干净是什么原因hcv9jop7ns2r.cn 什么叫伪娘hcv9jop8ns1r.cn 蛋蛋冰凉潮湿什么原因cl108k.com 引产和流产有什么区别hcv8jop7ns6r.cn 纯净水是什么水hcv9jop5ns8r.cn
百度