Close window automatically after printing dialog closes

Solution 1:

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

Solution 2:

This is what I came up with, I don't know why there is a small delay before closing.

 window.print();
 setTimeout(window.close, 0);

Solution 3:

Sure this is easily resolved by doing this:

      <script type="text/javascript">
         window.onafterprint = window.close;
         window.print();
      </script>

Or if you want to do something like for example go to the previous page.

    <script type="text/javascript">
        window.print();
        window.onafterprint = back;

        function back() {
            window.history.back();
        }
    </script>

Solution 4:

Just:

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

It works.

Solution 5:

I just want to write what I have done and what has worked for me (as nothing else I tried had worked).

I had the problem that IE would close the windows before the print dialog got up.

After a lot of trial and error og testing this is what I got to work:

var w = window.open();
w.document.write($('#data').html()); //only part of the page to print, using jquery
w.document.close(); //this seems to be the thing doing the trick
w.focus();
w.print();
w.close();

This seems to work in all browsers.