我有这样的代码:
hideStuff();
window.print();
showStuff();
因此,hideStuff()
会隐藏页面上的某些元素,以便它们不会打印,而showStuff()
会在打印对话框关闭后恢复这些隐藏的元素。
这适用于Safari 第一次时单击打印按钮,但如果我取消打印对话框,则返回页面并再次单击打印按钮, Safari会弹出一条消息,显示“此网页正在尝试打印。您要打印此网页吗?”如果我继续,结果打印预览包含页面的所有元素,甚至是那些应该被隐藏的元素。
问题似乎是“你确定”对话框延迟打开window.print()
,但它确实允许javascript继续。即showStuff()
立即运行,而不是在打印对话框关闭后运行。
当“你确定”框打开时,我该怎么做才能停止执行?
谢谢!
答案 0 :(得分:0)
我遇到了同样的问题,开始思考-当用户在该确认对话框中点击取消时,可能触发什么事件?
事实证明,我们的超级英雄事件很少onfocus
。每当用户直接单击“取消”或在键盘上按 Esc 时,就会触发该事件。
因此,基于此发现的解决方法可能大致如下:
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();
}