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

页面刷新后SweetAlert2年龄验证模态框无法弹出问题

故障原因

你的代码有3个核心问题导致刷新后模态框不触发:

  • localStorage键名使用错误:你把后端渲染的模板变量ageVerification直接当localStorage的存储键使用,如果后端返回的{{$ageVerification}}是空值、未定义,你写入的存储键就是空字符串,刷新后根本读不到之前写入的状态。
  • 条件判断逻辑漏洞:判断条件为if(ageVerification || localStorage.getItem(ageVerification) === 'false'),如果用户验证通过后后端把$ageVerification置空,第一个判断条件直接失效,加上前面的键名读取错误,第二个条件也不会成立,模态框自然不会触发。
  • 状态写入时机错误:你在模态框的didRender钩子(模态框刚渲染完成,用户还没做任何操作时)就把localStorage状态写成false,既不符合逻辑,也没有做禁止绕过的限制。
修复后代码
const blurContent = $('#global_wrap')
// 固定localStorage存储键,不要用动态模板值当键
const AGE_VERIFY_STORAGE_KEY = 'age_verification_passed'
// 后端传入的初始验证标记:后端判断用户未完成验证时值为true
const needAgeVerify = Boolean('{{$ageVerification}}')

function showModal(){
  Swal.fire({
    title: 'Confirm your age',
    text: 'You must be at least 18 years old to enter',
    icon: 'question',
    showCancelButton: true,
    confirmButtonText: 'I am over 18',
    cancelButtonText: 'I am under 18',
    confirmButtonColor: '#ee5934',
    allowEscapeKey: false,
    allowEnterKey: false,
    allowOutsideClick: false, // 禁止点击外部关闭模态框绕过验证
  }).then((result) => {
    if(result.isConfirmed){
      // 用户验证通过,清除模糊效果,标记本地状态为已通过
      blurContent.removeAttr('style')
      localStorage.setItem(AGE_VERIFY_STORAGE_KEY, 'true')
    }
    if(result.dismiss === Swal.DismissReason.cancel){
      // 用户选择未满18,锁死页面不允许关闭提示
      Swal.fire({
        title: 'Declined',
        text: 'Unfortunately, you cannot use this site',
        icon: 'error',
        showConfirmButton: false,
        allowOutsideClick: false,
        allowEscapeKey: false,
        didOpen: () => {
          // 直接清空页面内容,避免通过调试工具绕过限制
          blurContent.html('')
        }
      })
    }
  })
}

// 判断逻辑:只要本地没有明确的已验证通过标记,就触发验证流程
const isVerified = localStorage.getItem(AGE_VERIFY_STORAGE_KEY) === 'true'
if(needAgeVerify && !isVerified) {
  // 先加模糊效果再弹框,避免页面内容提前泄露
  blurContent.css('filter', 'blur(20px)')
  showModal()
}
关键修改说明
  • 固定localStorage键名为固定字符串,彻底解决动态模板值为空导致的存储、读取失败问题
  • 修正判断逻辑:只有本地明确标记为验证通过才不弹框,未完成验证的用户无论刷新多少次都会触发模态框
  • 调整状态写入时机:只有用户主动点击确认已满18岁,才会写入验证通过标记,模态框渲染阶段不再写入无效状态
  • 补充绕过限制:禁止点击模态框外部、按ESC键关闭验证弹窗,用户选择未满18岁时直接清空页面内容锁死访问

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 15:09:46