【发布时间】:2017-02-14 10:45:59
【问题描述】:
我在 JavaScript 中的页面打印存在特定问题。我需要在删除所有脚本的另一个选项卡上打开我的页面(这种方式:$(document).get(0).documentElement.innerHTML.replace(/<script[^>]+>.*?<\/script>/gi, ''),然后在新选项卡中调用window.print(),然后关闭它。
这是因为脚本中的错误会导致打印出现问题。负责整个打印的代码:
var w = window.open();
w.document.write(
$(document).get(0).documentElement.innerHTML.replace(/<script[^>]+>.*?<\/script>/gi,'')
);
w.document.close();
var loadingImagesInterval = setInterval(function() {
var imgs = w.document.querySelectorAll('img');
for (var i = 0; i < imgs.length; i++) {
if (!imgs[i].complete) return;
}
clearInterval(loadingImagesInterval);
w.focus();
w.print();
w.close();
}, 100);
基本上,问题在于,在 iOS 上,w.print() 似乎不会阻止代码执行,直到在打印视图中确认/取消,然后立即调用 w.close()。所有其他浏览器都可以正常工作:Mac Chrome、Mac Safari、IE11、Mac Firefox。一切都好。只是不是 iOS Safari。
我尝试了这段代码,但效果不佳:
w.matchMedia('print').addListener(function(mql) {
if (!mql.matches) {
w.close();
}
})
有没有更好的方法来处理我的问题?
【问题讨论】:
-
我仍然坚持这一点。你有想过这个吗?