我有这样的代码:
hideStuff();
window.print();
showStuff();
因此,hideStuff()
隐藏页面上的某些元素,这样它们就不会打印,而 showStuff()
会在打印对话框关闭后恢复那些隐藏的元素。
这在我第一次单击打印按钮时在 Safari 上有效,但如果我随后取消打印对话框,返回页面并再次单击打印按钮, Safari 弹出一条消息,内容为“此网页正在尝试打印。您要打印此网页吗?”然后如果我继续,生成的打印预览包含页面的所有元素,甚至是那些应该隐藏的元素。
问题似乎是“您确定吗”对话框延迟打开 window.print()
,但它确实允许 javascript 继续。是,showStuff()
立即运行,而不是在打印对话框关闭之后。
当“您确定”框打开时,我该怎么做才能停止执行?
谢谢!
最佳答案
我遇到了同样的问题,我的调查表明,只要用户点击 Cancel(或 Esc 按钮,就会触发 onfocus
事件键盘)关闭该确认对话框。
因此,基于 onfocus
事件的解决方法可能如下所示:
function safariPrint() {
// Safari 12, macOS
if (!window.onafterprint) {
const onAfterPrint = mql => {
if (!mql.matches) {
showStuff();
// printing is finished => unsubscribe to avoid leaks
if (mediaQueryList.removeEventListener) {
mediaQueryList.removeEventListener('change', onAfterPrint);
} else {
mediaQueryList.removeListener(onAfterPrint);
}
}
window.onfocus = null;
};
// a tiny polyfill for a plain onafterprint
// to handle standard window.print() dialog events
const mediaQueryList = window.matchMedia('print');
if (mediaQueryList.addEventListener) {
mediaQueryList.addEventListener('change', onAfterPrint);
} else {
mediaQueryList.addListener(onAfterPrint);
}
// if a user cancels printing in Safari's print confirmation dialog
// then we will trigger a cleanup
window.focus();
window.onfocus = () => {
onAfterPrint(mediaQueryList);
};
}
hideStuff();
window.print();
}
关于javascript - Safari ,JavaScript : wait for print confirmation window,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50455545/