IE had (has?) the onbeforeprint and onafterprint events: you could wait for that, but it would only work on IE (which may or may not be ok).
Alternatively, you could try and wait for the focus to return to the window from the print dialog and close it. Amazon Web Services does this in their invoice print dialogs: you hit the print button, it opens up the print-friendly view and immediately opens up the printer dialog. If you hit print or cancel the print dialog closes and then the print-friendly view immediately 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:
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:
Using Chrome I tried for a while to get the window.onfocus=function() { window.close(); } and the
<body ... onfocus="window.close()">
to work. My results:
I had closed my print dialogue, nothing happened.
I changed window/tabs in my browser, still nothing.
changed back to my first window/tab and then the window.onfocus event fired closing the window.
I also tried <body onload="window.print(); window.close()" > which resulted in the window closing before I could even click anything in the print dialogue.
I couldn't use either of those.
So I used a little Jquery to monitor the document status and this code works for me.
<script type="text/javascript">
var document_focus = false; // var we use to monitor document focused status.
// Now our event handlers.
$(document).focus(function() { document_focus = true; });
$(document).ready(function() { window.print(); });
setInterval(function() { if (document_focus === true) { window.close(); } }, 500);
</script>
Just make sure you have included jquery and then copy / paste this into the html you are printing. If the user has printed, saved as PDF or cancelled the print job the window/tab will auto self destruct. Note: I have only tested this in chrome.
Edit
As Jypsy pointed out in the comments, document focus status is not needed. You can simply use the answer from noamtcohen, I changed my code to that and it works.
The following solution is working for IE9, IE8, Chrome, and FF newer versions as of 2014-03-10.
The scenario is this: you are in a window (A), where you click a button/link to launch the printing process, then a new window (B) with the contents to be printed is opened, the printing dialog is shown immediately, and you can either cancel or print, and then the new window (B) closes automatically.
The following code allows this. This javascript code is to be placed in the html for window A (not for window B):
/**
* Opens a new window for the given URL, to print its contents. Then closes the window.
*/
function openPrintWindow(url, name, specs) {
var printWindow = window.open(url, name, specs);
var printAndClose = function() {
if (printWindow.document.readyState == 'complete') {
clearInterval(sched);
printWindow.print();
printWindow.close();
}
}
var sched = setInterval(printAndClose, 200);
};
The button/link to launch the process has simply to invoke this function, as in:
There's lots of pain getting stuff like this to work across browsers.
I was originally looking to do the same sort of thing - open a new page styled for print, print it using JS, then close it again. This was a nightmare.
In the end, I opted to simply click-through to the printable page and then use the below JS to initiate a print, then redirect myself to where I wanted to go when done (with a variable set in PHP in this instance).
I've tested this across Chrome and Firefox on OSX and Windows, and IE11-8, and it works on all (although IE8 will freeze for a bit if you don't actually have a printer installed).
Happy hunting (printing).
<script type="text/javascript">
window.print(); //this triggers the print
setTimeout("closePrintView()", 3000); //delay required for IE to realise what's going on
window.onafterprint = closePrintView(); //this is the thing that makes it work i
function closePrintView() { //this function simply runs something you want it to do
document.location.href = "'.$referralurl.'"; //in this instance, I'm doing a re-direct
}
</script>
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 worked best for me injecting the HTML into the popup such as <body onload="window.print()"...
The above works for IE, Chrome, and FF (on Mac) but no FF on Windows.
This worked for me in FF 36, Chrome 41 and IE 11. Even if you cancel the print, and even if you closed the print dialog with the top-right "X".
var newWindow=window.open();
newWindow.document.open();
newWindow.document.write('<HTML><BODY>Hi!</BODY></HTML>'); //add your content
newWindow.document.close();
newWindow.print();
newWindow.onload = function(e){ newWindow.close(); }; //works in IE & FF but not chrome
//adding script to new document below makes it work in chrome
//but alone it sometimes failed in FF
//using both methods together works in all 3 browsers
var script = newWindow.document.createElement("script");
script.type = "text/javascript";
script.text = "window.close();";
newWindow.document.body.appendChild(script);
Enable window to print and close itself based on a query parameter.
Requires jQuery. Can be done in _Layout or master page to work with all pages.
The idea is to pass a param in the URL telling the page to print and close, if the param is set then the jQuery “ready” event prints the window, and then when the page is fully loaded (after printing) the “onload” is called which closes the window. All this seemingly extra steps are to wait for the window to print before closing itself.
In the html body add and onload event that calls printAndCloseOnLoad(). In this example we are using cshtm, you could also use javascript to get param.
This is what worked for me (2018/02). I needed a seperate request because my print wansn't yet on screen.
Based on some of the excellent responses above, for which i thank you all, i noticed:
w.onload must not be set before w.document.write(data).
It seems strange because you would want to set the hook beforehand. My guess: the hook is fired already when opening the window without content. Since it's fired, it won't fire again. But, when there is still processing going on with a new document.write() then the hook will be called when processing has finished.
w.document.close() still is required. Otherwise nothing happens.
I've tested this in Chrome 64.0, IE11 (11.248), Edge 41.16299 (edgeHTML 16.16299), FF 58.0.1 .
They will complain about popups, but it prints.
function on_request_print() {
$.get('/some/page.html')
.done(function(data) {
console.log('data ready ' + data.length);
var w = window.open();
w.document.write(data);
w.onload = function() {
console.log('on.load fired')
w.focus();
w.print();
w.close();
}
console.log('written data')
//this seems to be the thing doing the trick
w.document.close();
console.log('document closed')
})
}
I guess the best way is to wait for the document (aka DOM) to load properly and then use the print and close functions. I'm wrapping it in the Document Ready function (jQuery):
Worth to notice is that the above is put on my "printable page" (you can call it "printable.html" that I link to from another page (call it linkpage.html if you want):
<script>
function openNewPrintWindow(){
var newWindow=window.open('http://printable.html'); //replace with your url
newWindow.focus(); //Sets focus window
}
</script>
And for the copy-paste-developer who's just looking for a solution, here is the "trigger" to the function above (same page):
This works for me perfectly @holger, however, i have modified it and suit me better, the window now pops up and close immediately you hit the print or cancel button.
function printcontent()
{
var disp_setting="toolbar=yes,location=no,directories=yes,menubar=yes,";
disp_setting+="scrollbars=yes,width=300, height=350, left=50, top=25";
var content_vlue = document.getElementById("content").innerHTML;
var w = window.open("","", disp_setting);
w.document.write(content_vlue); //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();
}"
onafterprint works good to me on desktop browser, no with smartphone, so y make something like this and work, there are many solutions, so try many anyway.