Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close window automatically after printing dialog closes

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?

like image 572
Tsundoku Avatar asked Jun 23 '11 21:06

Tsundoku


People also ask

How to close window after print in javascript?

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.

How to close print dialog box in javascript?

You can check window. close. This will close the current window.

How do you fix Scripts may close only the windows that were opened by it?

Scripts may close only the windows that were opened by it. A workaround now is redirect user to another page rather than close the window, you could redirect user to a notification page to show "The items has been closed successfully" using window. location.


1 Answers

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); } 
like image 118
serfer2 Avatar answered Sep 27 '22 18:09

serfer2