如何更新localStorage存储的时间戳实现定时弹出模态框
localStorage控制模态框按间隔弹出实现方案
需求说明
需要通过localStorage存储、更新时间戳,实现间隔指定时长后触发模态框展示:
- 测试阶段设置1分钟有效期,页面刷新时仅当时间戳过期(距上次存储时长超过1分钟)才弹出模态框
- 最终目标为单个用户每日仅展示一次该模态框
初始问题代码
最初编写的代码仅能在首次刷新时弹出模态框并写入localStorage键值,达到1分钟有效期后刷新页面,模态框并未按预期弹出,问题代码如下:
$(document).ready(function() { function shouldShowModal() { const lastTimestamp = localStorage.getItem("modalTimestamp"); if (!lastTimestamp) { return true; } const parsedTimestamp = parseInt(lastTimestamp, 10); let expiryLimit = new Date(parsedTimestamp); expiryLimit = expiryLimit.setMinutes(expiryLimit.getMinutes() + 1); return new Date() > expiryLimit; } if (window.localStorage) { const currentUser = '<%= current_user %>'; const currentTime = new Date($.now()); if (currentUser && shouldShowModal()) { swal ({ icon: 'warning', text: 'Notice text here.', closeOnClickOutside: false, button: 'ok' }) localStorage.setItem('modalTimestamp', currentTime); } } }
问题原因&修复方法
代码失效的核心原因有两个:
- 写入localStorage时直接传入了Date对象:localStorage仅支持存储字符串类型,传入Date对象会被自动转换为可读时间字符串,后续用
parseInt解析时无法得到合法的时间戳数值,导致过期判断逻辑永远返回false,达到有效期也不会弹出模态框 - 测试阶段的1分钟有效期需要调整为24小时,匹配「单个用户每日仅展示一次」的最终需求
修复时只需要在写入localStorage时调用getTime()方法获取毫秒级数值时间戳,同时调整过期时长计算逻辑即可,修复后可正常运行的代码如下:
$(document).ready(function() { function shouldShowModal() { const lastTimestamp = localStorage.getItem("modalTimestamp"); if (!lastTimestamp) { return true; } const parsedTimestamp = parseInt(lastTimestamp, 10); let expiryLimit = new Date(parsedTimestamp); expiryLimit = expiryLimit.setHours(expiryLimit.getHours() + 24); return new Date() > expiryLimit; } if (window.localStorage) { const currentUser = '<%= current_user %>'; const currentTime = new Date(); if (currentUser && shouldShowModal()) { swal ({ icon: 'warning', text: 'Notice text here.', closeOnClickOutside: false, button: 'ok' }) localStorage.setItem('modalTimestamp', currentTime.getTime()); } } }
如果需要切回测试模式,只需要把
setHours部分改回setMinutes加1分钟的逻辑即可,时间戳存储逻辑不需要再改动。
内容的提问来源于stack exchange,提问作者StephenW
相关产品推荐
相关产品推荐

