Close window automatically after printing dialog closes

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

Leave a Comment