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

如何在用户离开页面时触发JavaScript退出弹窗?

页面离开时触发弹窗的解决方案

你遇到的问题在于unload事件在现代浏览器中被严格限制,触发时页面已进入卸载流程,无法正常渲染自定义弹窗。以下是可行的替代方案:

核心修改:使用beforeunload事件

beforeunload事件在页面即将卸载时触发,此时页面资源仍完整,能支持弹窗渲染。同时需要处理浏览器的事件限制:

修改后的代码

(function(){
var expireKey = 'newsletter';      // localStorage中存储的时间戳键名
var popupId   = '#get-newsletter'; // 要显示的弹窗ID

function maybeShowPopup(e) {
    // 检查今日是否已显示过弹窗
    if ( window.localStorage ) {
        var nextPopup = localStorage.getItem( expireKey );
        // 将存储的时间戳转为数字,避免字符串比较错误
        if (parseInt(nextPopup) > new Date().getTime()) {
            return;
        }

        var expires = new Date();
        expires = expires.setHours(expires.getHours() + 24);
        localStorage.setItem( expireKey, expires );
    }
        
    DiviPopup.openPopup( popupId );
    // 触发浏览器默认确认逻辑,确保自定义弹窗能正常执行
    e.preventDefault();
    e.returnValue = '';
}

// 替换unload为beforeunload事件
jQuery(window).on('beforeunload', maybeShowPopup );
})()

补充方案:应对浏览器弹窗限制

部分浏览器(如Chrome、Edge)会限制beforeunload中的自定义弹窗,此时可以结合visibilitychange事件(页面切换到后台时触发)作为补充,覆盖用户切换标签、最小化窗口等场景:

// 新增页面可见性变化监听
jQuery(document).on('visibilitychange', function() {
    if (document.visibilityState === 'hidden') {
        maybeShowPopup();
    }
});

注意事项

  • 浏览器对页面卸载时的弹窗有严格管控,目的是防止恶意广告,因此自定义弹窗可能在部分场景下被拦截,这是浏览器的默认行为无法完全规避。
  • 原代码中nextPopup > new Date()的比较存在问题,因为localStorage存储的是字符串类型的时间戳,需要用parseInt转为数字后再和当前时间戳(new Date().getTime())比较。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 07:00:22