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

如何仅在网站关闭时删除Cookie,避免刷新时重复弹出模态框?

解决方法

你的问题根源在于beforeunload事件会在页面刷新、跳转、窗口关闭时全部触发,导致刷新后Cookie被删除,模态框再次弹出。要实现仅关闭网站时删除Cookie,核心是区分「刷新/跳转」和「窗口关闭」两种行为,以下是两种可行方案:

方案一:使用Navigation API(现代浏览器推荐)

现代浏览器提供的navigation API可直接获取导航类型,精准判断是否为刷新行为:

$(document).ready(function () {
    // 仅在首次加载或非刷新导航时,检查Cookie并弹出模态框
    if (!window.navigation || navigation.type !== 1) {
        if ($.cookie("announcement") == null) {
            $.cookie("announcement", "yes");
            $("#large").modal("show");
        }
    }

    $(window).on("beforeunload", function () {
        // 仅当不是刷新行为时,删除Cookie
        if (navigation.type !== 1) {
            $.removeCookie("announcement");
        }
    });
});

说明

  • navigation.type取值:0=首次加载,1=页面刷新,2=页面跳转
  • 仅在非刷新场景下处理Cookie和模态框,同时仅在窗口关闭/跳转时删除Cookie

方案二:定时器标记法(兼容旧浏览器)

如果需要兼容不支持Navigation API的旧浏览器,可通过定时器标记区分行为:

let isRefreshing = false;

// 页面加载后延迟执行,避开刷新的时间差
window.addEventListener('load', function() {
    setTimeout(() => {
        if ($.cookie("announcement") == null) {
            $.cookie("announcement", "yes");
            $("#large").modal("show");
        }
    }, 100);
});

$(window).on("beforeunload", function () {
    // 刷新时会先触发beforeunload,标记为刷新状态
    isRefreshing = true;
});

$(window).on("unload", function () {
    // 关闭窗口时,isRefreshing未被标记,此时删除Cookie
    if (!isRefreshing) {
        $.removeCookie("announcement");
    }
});

关键注意点

  • 确保删除Cookie时和设置Cookie时使用相同的路径/域参数,比如Cookie设置了path: "/",删除时也要写$.removeCookie("announcement", { path: "/" }),否则可能无法正确删除
  • 部分现代浏览器会限制beforeunload/unload事件中的异步操作,删除Cookie需同步执行

内容的提问来源于stack exchange,提问作者Ahmet Enes Söylemez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 11:45:37