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

Firefox 89中afterprint事件提前触发导致页面后退失效怎么解决?

兼容解决方案

针对Firefox 89+版本afterprint事件提前触发的问题,可采用以下兼容方案:

  • 方案1:结合afterprint事件与窗口焦点检测
    原理是打印对话框打开时页面窗口处于失焦状态,只有用户关闭对话框后窗口才会重新获得焦点,以此判定打印流程真正结束:
const afterPrint = () => {
    const onWindowFocus = () => {
        this.location.back();
        window.removeEventListener('focus', onWindowFocus);
        window.removeEventListener('afterprint', afterPrint);
    };
    if (document.hasFocus()) {
        onWindowFocus();
    } else {
        window.addEventListener('focus', onWindowFocus);
    }
};

window.addEventListener('afterprint', afterPrint);
window.print();
  • 方案2:使用打印媒体查询监听兜底
    通过监听打印媒体查询的状态变化判定打印流程是否结束,兼容范围更广:
const printMedia = window.matchMedia('print');
const onPrintStatusChange = (e) => {
    // 匹配规则从print变为screen,代表打印结束
    if (!e.matches) {
        const execBack = () => {
            this.location.back();
            window.removeEventListener('focus', execBack);
            printMedia.removeEventListener('change', onPrintStatusChange);
        };
        document.hasFocus() ? execBack() : window.addEventListener('focus', execBack);
    }
};
printMedia.addEventListener('change', onPrintStatusChange);
window.print();
  • 可选优化:加短延迟兜底
    针对极端场景可在执行回退前添加100~200ms的延迟,进一步降低拦截概率:
setTimeout(() => {
    this.location.back();
}, 150);

以上方案均兼容Chrome、Firefox全版本、Safari等主流浏览器。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 07:45:05