Close window automatically after printing dialog closes

Tsundoku picture Tsundoku · Jun 23, 2011 · Viewed 184.7k times · Source

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?

Answer

serfer2 picture serfer2 · Aug 22, 2012

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();

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.

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.

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.

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 ;-)

Update:

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); }