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
相关产品推荐
相关产品推荐

