You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于localStorage实现用户首次登录90天内仅显示一次Modal的方案

问题根因

原有实现仅在localStorage中存储了单个用户的邮箱标识和弹窗状态,切换用户登录时旧用户的存储值会被新用户覆盖,导致同一设备上切换回历史登录用户时,原本已触发过的弹窗会重复展示。

解决方案

使用数组存储所有已触发过弹窗的用户邮箱是可行方案,利用JSON序列化/反序列化实现数组在localStorage中的存取即可解决问题。

核心实现逻辑

  • 先校验当前距离指定起始日期是否不超过90天、用户是否处于登录状态
  • 读取localStorage中存储的已弹窗用户邮箱列表,不存在则初始化为空数组
  • 校验当前登录用户邮箱是否在列表中:
    • 不在列表内:触发弹窗,同时将当前用户邮箱加入列表后序列化存回localStorage
    • 在列表内:不触发弹窗

最终实现代码

window.onload = function() {
    (function() {
        const startDate = new Date('7/13/2021');
        const currentDate = new Date();
        const diffTime = Math.abs(currentDate - startDate);
        const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
        const emailName = '@if(!isNull(tctx.getActor().getEmail())){@tctx.getActor().getEmail()}'; 
                    
    if(diffDays <= 90 && emailName !== ''){ 

        const emailLogged = localStorage.getItem('emailLogged');

        if(emailLogged === null){
            localStorage.setItem('emailLogged', '[]') 
        }

        const oldEmailLogged = JSON.parse(localStorage.getItem('emailLogged'))
        const arraySameValue = oldEmailLogged || [];

        if(arraySameValue.indexOf(emailName) == -1){ 

            arraySameValue.push(emailName) 
            const stringRepresentingArray = JSON.stringify(arraySameValue);
            window.localStorage.setItem("emailLogged", stringRepresentingArray);
                            
            $('#staticBackdrop').modal('show'); 
        }
      }
   })();
};

内容的提问来源于stack exchange,提问作者fikfe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 08:24:03