打印对话框关闭后自动关闭窗口 [英] Close window automatically after printing dialog closes

查看:525
本文介绍了打印对话框关闭后自动关闭窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户点击按钮时,我打开了一个标签。在 onload 上我打开了打印对话框,但是用户问我是否有可能在它发送到打印机后打印,如果标签可以关闭。我不确定是否可以这样做。我已经尝试使用 setTimeout(); ,但它不是一个定义的时间段,因为用户可能会分散注意力并且不得不重新打开选项卡。有没有办法实现这个目标?

I have a tab open when the user clicks a button. On the onload I have it bring up the print dialog, but the user asked me whether it was possible that after it sends to the printer to print, if the tab could close itself. I am not sure whether this can be done. I have tried using setTimeout();, but it's not a defined period of time since the user might get distracted and have to reopen the tab. Is there any way to accomplish this?

推荐答案

如果您尝试在print()调用之后关闭窗口,它可能会立即关闭窗口,print()将无法正常工作。这就是你不应该做的

if you try to close the window just after the print() call, it may close the window immediately and print() will don't work. This is what you should not do:

window.open();
...
window.print();
window.close();

此解决方案适用于Firefox,因为在print()调用中,它会一直等到打印完成并且然后它继续处理javascript并关闭()窗口。
IE将失败,因为它调用close()函数而不等待print()调用完成。弹出窗口将在打印完成之前关闭。

This solution will work in Firefox, because on print() call, it waits until printing is done and then it continues processing javascript and close() the window. IE will fail with this because it calls the close() function without waiting for the print() call is done. The popup window will be closed before printing is done.

解决它的一种方法是使用onafterprint事件,但我不建议你这样做仅适用于IE。

One way to solve it is by using the "onafterprint" event but I don' recommend it to you becasue these events only works in IE.

关闭打印对话框(打印完成或取消)后关闭弹出窗口的最佳方式。此时,弹出窗口将被聚焦,您可以使用onfocus事件关闭弹出窗口。

The best way is closing the popup window once the print dialog is closed (printing is done or cancelled). At this moment, the popup window will be focussed and you can use the "onfocus" event for closing the popup.

为此,只需插入此javascript嵌入代码你的弹出窗口:

To do this, just insert this javascript embedded code in your popup window:

<script type="text/javascript">
window.print();
window.onfocus=function(){ window.close();}
</script>

希望这个肝脏; - )

Hope this hepls ;-)

更新:

对于新的Chrome浏览器,它可能仍会过早关闭见这里。我已实现此更改,它适用于所有当前浏览器:2/29/16

For new chrome browsers it may still close too soon see here. I've implemented this change and it works for all current browsers: 2/29/16

        setTimeout(function () { window.print(); }, 500);
        window.onfocus = function () { setTimeout(function () { window.close(); }, 500); }

这篇关于打印对话框关闭后自动关闭窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆