110

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?

Nathaniel Ford
  • 20,545
  • 20
  • 91
  • 102
Tsundoku
  • 9,104
  • 29
  • 93
  • 127
  • possible duplicate of [onbeforeprint() and onafterprint() equivalent for non IE browsers (PHP, MySQL, JavaScript, HTML)](http://stackoverflow.com/questions/3339789/onbeforeprint-and-onafterprint-equivalent-for-non-ie-browsers-php-mysql-j) – senderle Jul 07 '12 at 02:58
  • See [this answer](http://stackoverflow.com/questions/3339789/onbeforeprint-and-onafterprint-equivalent-for-non-ie-browsers-php-mysql-ja). – Kirk Strobeck Jun 23 '11 at 22:05

40 Answers40

139

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); }
Pakk
  • 1,299
  • 2
  • 18
  • 36
serfer2
  • 2,573
  • 1
  • 23
  • 17
  • For what it's worth, this seems to fail in IE8. The window closes immediately before the print dialog shows. – Heath Nov 08 '13 at 20:19
  • 16
    this does not appear to work for chrome at this point, since chrome handles printing internally, the window will not lose focus when the print dialog loads, and therefore won't regain focus when printing is done. Any way to make this work for Chrome? – jlbriggs Nov 18 '13 at 20:29
  • The window.onfocus trick works on Chrome beta channel as of now – guidod Mar 12 '14 at 21:30
  • focus event is fired twice in IE11 leading to two confirm dialogs (something like "do you really want to close?") after printing. – moeTi Jan 21 '15 at 10:08
  • 6
    As of Feb. 2016 this and NONE of the other focus() based answers works in Chrome anymore. The only working solution is that of @noamtcohen (sadly with a very low vote count). – Jpsy Feb 25 '16 at 13:12
  • It does NOT work in FireFox. The data dialog is always closed after 0.5 second (as your code) while the printer dialog is still appearing. I am using FF version 47.0. – NoName Aug 02 '16 at 06:43
  • doesn't work, use window.print(); setTimeout(window.close, 0); as in other answer. – Astra Bear Aug 29 '16 at 07:39
  • thanks for the update. Works on my Chorme (even if I was using a different window name) var mywindow = window.open('test.txt'); // mywindow.focus(); // necessary for IE >= 10 mywindow.print(); setTimeout(function () { myWindow.print(); }, 500); mywindow.onfocus = function () { setTimeout(function () { mywindow.close(); }, 500); } – gthuo Nov 04 '16 at 13:13
  • 3
    I think the latest version of Chrome is not showing the print dialog until images on the page have loaded, but it's executing the close before, so the page closes before it loads (print dialog never shows). To fix `window.onload = function () { window.print(); setTimeout(window.close, 500); };` – Brian Leishman Sep 29 '17 at 20:28
  • @BrianLeishman this will result in a "Blocked a frame with origin "[url]" from accessing a cross-origin frame." error. – Rover Oct 09 '18 at 05:47
  • 11
    The above solution don not work any more, please add event listener **onafterprint** to close window window.onafterprint = function(){ window.close()}; – Rahat Hameed Dec 31 '19 at 10:20
  • Try this: window.document.body.onfocus=function(){ window.close();} – Guilherme Correa Teixeira Feb 03 '20 at 12:53
  • 3
    The year is 2022 and onafterprint is now [supported by all major browsers](https://caniuse.com/?search=onafterprint) and is the easiest solution. – Michael T Jan 03 '22 at 12:49
100

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);
noamtcohen
  • 4,432
  • 2
  • 20
  • 14
  • 1
    It is interesting that this low-rated answer is currently the correct one. As of Feb. 2016 none of the focus() based answers works in Chrome anymore. This solution works in FF, Chrome and Safari on Windows and OS X, IE9+ , Android Chrome and IOS Safari. We only experienced confirmation dialogs in old IEs. All other close seamlessly. – Jpsy Feb 25 '16 at 13:11
  • 7
    As of Mar 17, this did not work for me exactly as is in Chrome (56) but adding some time to the time out worked. window.print(); setTimeout(window.close, 500); – jAC Mar 06 '17 at 02:34
  • As jAC mentioned, this needed more time for it to work. On mine, 10ms was not enough, but 100 was. It appears to be a matter of how long it takes to render the print-preview. With mine set to 10 ms, it only printed a partially rendered version of the page. With 100 I got the whole thing. – Jacob Ewing Apr 06 '17 at 15:45
  • 2
    To expand on that, it ~seems~ like the the timeout is paused once the print window is fully rendered (in chrome on a macbook anyway), and the remainder counted after the window is closed. – Jacob Ewing Apr 06 '17 at 15:48
  • 1
    You don't need the 0, it's the default – Brian Leishman Sep 29 '17 at 20:30
40

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>
Blaise
  • 13,139
  • 9
  • 69
  • 97
Samuel Bié
  • 783
  • 8
  • 11
  • window.close(); – Mustafa Oct 17 '19 at 05:54
  • Note: `window.onafterprint = window.close();` should be `window.onafterprint = window.close;` The former assigns the **result** of `window.close()` to `onafterprint`. This will cause `window.close()` to run immediately when the handler is set, and nothing to run when the `onafterprint` event is raised. The latter assigns `window.close` as the event handler, which is what we want. – Kei Oct 19 '20 at 01:55
  • 2
    Also, in some browsers, code execution pauses after `window.print();` until the print dialog is dismissed. When this happens, it is possible for the `onafterprint` event to be raised before `onafterprint` is assigned. Thus, it would be better for `window.onafterprint = window.close;` to come before `window.print();`. Otherwise, the approach used in this answer works better than the onfocus or setTimeout-based ones suggested by the other answers. – Kei Oct 19 '20 at 01:56
  • Note: this is now supported by all modern browsers, see compatibility chart on https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onafterprint#browser_compatibility – Blaise Jan 11 '21 at 15:50
14

Just:

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

It works.

Eric Rini
  • 1,830
  • 15
  • 20
Ying Style
  • 752
  • 2
  • 7
  • 25
  • 2
    This does not work reliably for me on chrome. Sometimes it works, but sometimes the window just immediately closes before the print dialog comes up. I can prevent that from happening by increasing the timeout to 5000, but then it sometimes takes up to 5 seconds for the window to close after printing. I'm not exactly sure what's happening here, but it doesn't seem likely to be robust across different browsers. – speedarius Aug 31 '15 at 17:24
  • 1
    As mentioned below, the full cross-browser solution is more intricate. – Eric Rini Dec 08 '15 at 19:20
  • 1
    Don't forget the: `Scripts may close only the windows that were opened by it.` warning. – Cas Bloem Feb 18 '16 at 14:26
  • The above solution don not work any more, please add event listener **onafterprint** to close window. `window.onafterprint = function(){ window.close()};` – Rahat Hameed Dec 31 '19 at 10:22
13

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.

Holger
  • 2,243
  • 17
  • 19
11

This code worked perfectly for me:

<body onload="window.print()" onfocus="window.close()">

When the page opens it opens the print dialog automatically and after print or cancel it closes the window.

Hope it helps,

Carsten
  • 11,287
  • 7
  • 39
  • 62
Victor Olaru
  • 111
  • 1
  • 2
  • this dose not work if you have opened pdf to print not html or jsp where then i may put onload body ? – shareef Nov 26 '17 at 07:15
  • Thank You for your post, this one worked for me because on mobile devices it doesn't display an error when saving to PDF. – Samuel Ramzan Dec 11 '21 at 04:15
11

Just wrap window.close by onafterprint event handler, it worked for me

printWindow.print();
printWindow.onafterprint = () => printWindow.close();
user10145303
  • 111
  • 1
  • 4
10

This is a cross-browser solution already tested on Chrome, Firefox, Opera by 2016/05.

Take in mind that Microsoft Edge has a bug that won't close the window if print was cancelled. Related Link

var url = 'http://...';
var printWindow = window.open(url, '_blank');
printWindow.onload = function() {
    var isIE = /(MSIE|Trident\/|Edge\/)/i.test(navigator.userAgent);
    if (isIE) {

        printWindow.print();
        setTimeout(function () { printWindow.close(); }, 100);

    } else {

        setTimeout(function () {
            printWindow.print();
            var ival = setInterval(function() {
                printWindow.close();
                clearInterval(ival);
            }, 200);
        }, 500);
    }
}
Heroselohim
  • 1,241
  • 1
  • 18
  • 23
7

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:

  1. I had closed my print dialogue, nothing happened.
  2. I changed window/tabs in my browser, still nothing.
  3. 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.

Nado11
  • 105
  • 1
  • 6
  • This solution causes the original window to hang if the user closes the popup with the "X" in the corner rather than selecting Cancel or Print. Same issue as Juan's solution, which @JFK pointed out originally. – Clayton Apr 10 '14 at 15:59
  • The above javascript is mean't to be placed in the html being printed whether opened in a popup or, as I do, in a new tab. Thus this javascript has no effect on the original window. – Nado11 Oct 28 '15 at 01:15
7

REF source reference

<script type="text/javascript">
  window.print();
  window.onafterprint = window.close;   
</script>
Rubén Ruíz
  • 453
  • 4
  • 9
6

This works well in Chrome 59:

window.print();
window.onmousemove = function() {
  window.close();
}
Max Hudson
  • 9,961
  • 14
  • 57
  • 107
6

This worked for me 11/2020 <body onafterprint="window.close()"> ... simple.

Thor88
  • 323
  • 3
  • 7
5

this one works for me:

<script>window.onload= function () { window.print();window.close();   }  </script>
arun.m
  • 131
  • 1
  • 3
5

The following worked for me:

function print_link(link) {
    var mywindow = window.open(link, 'title', 'height=500,width=500');   
    mywindow.onload = function() { mywindow.print(); mywindow.close(); }
}
J0e3gan
  • 8,740
  • 10
  • 53
  • 80
4

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:

openPrintWindow('http://www.google.com', 'windowTitle', 'width=820,height=600');
  • It works in Chrome as long as the user prints or cancels the operation BUT if the user closes the window (B), the window (A) hangs (did I say in Chrome?). Test (in Chrome) http://jsfiddle.net/qy6QV/2/show/ and close the window. Then try to reload it ... hung. – JFK Apr 10 '14 at 04:08
4

I tried many things that didn't work. The only thing that worked for me was:

window.print();
window.onafterprint = function () {
    window.close();
}

tested on chrome.

Zeyad
  • 537
  • 2
  • 7
  • 15
2
<!doctype html>
<html>
<script>
 window.print();
 </script>
<?php   
date_default_timezone_set('Asia/Kolkata');
include 'db.php'; 
$tot=0; 
$id=$_GET['id'];
    $sqlinv="SELECT * FROM `sellform` WHERE `id`='$id' ";
    $resinv=mysqli_query($conn,$sqlinv);
    $rowinv=mysqli_fetch_array($resinv);
?>
        <table width="100%">
           <tr>
                <td style='text-align:center;font-sie:1px'>Veg/NonVeg</td>  
            </tr>
            <tr>
                <th style='text-align:center;font-sie:4px'><b>HARYALI<b></th>  
            </tr>   
            <tr>
                <td style='text-align:center;font-sie:1px'>Ac/NonAC</td>  
            </tr>
            <tr>
                <td style='text-align:center;font-sie:1px'>B S Yedurappa Marg,Near Junne Belgaon Naka,P B Road,Belgaum - 590003</td>  
            </tr>
        </table>
        <br>    
        <table width="100%">
           <tr>
                <td style='text-align:center;font-sie:1'>-----------------------------------------------</td>  
            </tr>
        </table>

        <table  width="100%" cellspacing='6' cellpadding='0'>

            <tr>
                <th style='text-align:center;font-sie:1px'>ITEM</th>
                <th style='text-align:center;font-sie:1px'>QTY</th>
                <th style='text-align:center;font-sie:1px'>RATE</th>
                <th style='text-align:center;font-sie:1px'>PRICE</th>
                <th style='text-align:center;font-sie:1px' >TOTAL</th>
            </tr>

            <?php
            $sqlitems="SELECT * FROM `sellitems` WHERE `invoice`='$rowinv[0]'";
            $resitems=mysqli_query($conn,$sqlitems);
            while($rowitems=mysqli_fetch_array($resitems)){
            $sqlitems1="SELECT iname FROM `itemmaster` where icode='$rowitems[2]'";
            $resitems1=mysqli_query($conn,$sqlitems1);
            $rowitems1=mysqli_fetch_array($resitems1);
            echo "<tr>
                <td style='text-align:center;font-sie:3px'  >$rowitems1[0]</td>
                <td style='text-align:center;font-sie:3px' >$rowitems[5]</td>
                <td style='text-align:center;font-sie:3px' >".number_format($rowitems[4],2)."</td>
                <td style='text-align:center;font-sie:3px' >".number_format($rowitems[6],2)."</td>
                <td style='text-align:center;font-sie:3px' >".number_format($rowitems[7],2)."</td>
              </tr>";
                $tot=$tot+$rowitems[7];
            }

            echo "<tr>
                <th style='text-align:right;font-sie:1px' colspan='4'>GRAND TOTAL</th>
                <th style='text-align:center;font-sie:1px' >".number_format($tot,2)."</th>
                </tr>";
            ?>
        </table>
     <table width="100%">
           <tr>
                <td style='text-align:center;font-sie:1px'>-----------------------------------------------</td>  
            </tr>
        </table>
        <br>
        <table width="100%">
            <tr>
                <th style='text-align:center;font-sie:1px'>Thank you Visit Again</th>  
            </tr>
        </table>
<script>
window.close();
</script>
</html>

Print and close new tab window with php and javascript with single button click

2

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();
}"
2

jquery:

$(document).ready(function(){ 
  window.print();
  setTimeout(function(){ 
             window.close();
  }, 3000);
});
sshashank124
  • 31,495
  • 9
  • 67
  • 76
Armandof
  • 31
  • 2
1

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.

https://stackoverflow.com/a/11782214/1322092

var html = '<html><head><title></title>'+
               '<link rel="stylesheet" href="css/mycss.css" type="text/css" />'+
               '</head><body onload="window.focus(); window.print(); window.close()">'+
               data+
               '</body></html>';
Community
  • 1
  • 1
user1322092
  • 4,020
  • 7
  • 35
  • 52
1

Here's what I do....

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.

<body onload="sccPrintAndCloseOnLoad('@Request.QueryString["PrintAndClose"]');">

In the javascript add the function.

function printAndCloseOnLoad(printAndClose) {
    if (printAndClose) {
        // close self without prompting
        window.open('', '_self', ''); window.close();
    }
}

And jQuery ready event.

$(document).ready(function () {
    if (window.location.search.indexOf("PrintAndClose=") > 0)
        print();
});

Now when opening any URL, simply append the query string param “PrintAndClose=true” and it will print and close.

RitchieD
  • 1,831
  • 22
  • 21
1

To me, my final solution was a mix of several answers:

    var newWindow = window.open();
    newWindow.document.open();
    newWindow.document.write('<html><link rel="stylesheet" href="css/normalize-3.0.2.css" type="text/css" />'
            + '<link rel="stylesheet" href="css/default.css" type="text/css" />'
            + '<link rel="stylesheet" media="print" href="css/print.css" type="text/css" />');

    newWindow.document.write('<body onload="window.print();" onfocus="window.setTimeout(function() { window.close(); }, 100);">');
    newWindow.document.write(document.getElementById(<ID>).innerHTML);
    newWindow.document.write('</body></html>');
    newWindow.document.close();
    newWindow.focus();
Felipe
  • 16,649
  • 11
  • 68
  • 92
1

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')
    })
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<a onclick="on_request_print();">Print rapportage</a>
Remco
  • 435
  • 3
  • 10
1
const printHtml = async (html) => {
    const printable = window.open('', '_blank', 'fullscreen=no');
    printable.document.open();
    printable.document.write(`<html><body onload="window.print()">${html}</body></html>`);
    await printable.print();
    printable.close();
};

Here's my ES2016 solution.

Stuart
  • 21
  • 1
  • 1
    Hello Stuart, and welcome to Stack Overflow! Could you explain why this code works to help the OP and other users more? Thanks! – Auden Young Jul 20 '18 at 01:05
0

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>
boboshady
  • 39
  • 2
0

just use this java script

 function PrintDiv() {
    var divContents = document.getElementById("ReportDiv").innerHTML;
    var printWindow = window.open('', '', 'height=200,width=400');
    printWindow.document.write('</head><body >');
    printWindow.document.write(divContents);
    printWindow.document.write('</body></html>');
    printWindow.document.close();
    printWindow.print();
    printWindow.close();
}

it will close window after submit or cancel button click

Opal
  • 81,889
  • 28
  • 189
  • 210
user3373573
  • 5
  • 1
  • 5
0

On IE11 the onfocus event is called twice, thus the user is prompted twice to close the window. This can be prevented by a slight change:

<script type="text/javascript">
  var isClosed = false;
  window.print();
  window.onfocus = function() {
    if(isClosed) { // Work around IE11 calling window.close twice
      return;
    }
    window.close();
    isClosed = true;
  }
</script>
0

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);
James Bell
  • 889
  • 2
  • 10
  • 16
0
setTimeout(function () { window.print(); }, 500);
        window.onfocus = function () { setTimeout(function () { window.close(); }, 500); }

It's work perfectly for me. Hope it helps

Klajdi Dosti
  • 174
  • 2
  • 13
0

This works for me on Chrome (haven't tried on others)

$(function(){
    window.print();
    $("body").hover(function(){
        window.close();
    });
});
emmmm
  • 123
  • 2
  • 5
0

I tried this and it works

var popupWin = window.open('', 'PrintWindow', 
'width=650,height=650,location=no,left=200px');
popupWin.document.write(data[0].xmldata);
popupWin.print();
popupWin.close();
0

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

<script>
$(document).ready(function () {
window.print();
window.close();
});
</script>

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

<button onclick="openNewPrintWindow()">Print</button>

So it will

  1. Open a new window when you click Print
  2. Trigger the (browser) print dialogue after page load
  3. Close window after printed (or cancelled).

Hope you are having fun!

Rbbn
  • 627
  • 7
  • 13
0

simple add:

<html>
<body onload="print(); close();">
</body>
</html>
Somwang Souksavatd
  • 4,947
  • 32
  • 30
0

try this:

var xxx = window.open("","Printing...");
xxx.onload = function () {
     setTimeout(function(){xxx.print();}, 500);
     xxx.onfocus = function () {
        xxx.close();
     }  
}
0

An entirely different approach using native things only

First, add the following in the page that is to be printed

<head>
<title>printing please wait</title>
<META http-equiv=Refresh content=2;url="close.html">
</head>
<body onLoad="window.print()">

Then make close.html with following content

<body onLoad="window.close()"></body>

Now when the print dialogue is displayed, the page will remain open. As soon as the print or cancel task is done, the page will close like a breeze.

0
<!--- ON click print button, get print and on click close button of print window, get print window closed--->

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Print preview</title>

 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
    $(function () {
        $("#testid").click(function () {
            var sWinHTML = document.getElementById('content_print').innerHTML;
            var winprint = window.open("", "");
            winprint.document.open();
            winprint.document.write('<html><head>');
            winprint.document.write('<title>Print</title>');
            winprint.document.write('</head><body onload="window.focus(); window.print(); window.close()">');
            winprint.document.write(sWinHTML);
            winprint.document.write('</body></html>');
            winprint.document.close();
            winprint.focus();
        })
    })
</script>
</head>
 <body>

  <form id="form-print">
    <div id="content_print">
    <h3>Hello world</h3>
    <table cellpadding="0" cellspacing="0" width="100%">
    <thead>
    <tr>
    <th style="text-align:left">S.N</th>
    <th style="text-align:left">Name</th>
    </tr>
    </thead>
    <tbody>
    <tr>
      <td>1</td>
      <td>Bijen</td>
    </tr>
    <tr>
      <td>2</td>
      <td>BJ</td>
    </tr>
    </tbody>
    </table>
    </div>
    <button type="button" id="testid"/>Print</button>
</form>
</body>
</html>
Bijendra Ch
  • 417
  • 3
  • 4
0
document.addEventListener('DOMContentLoaded', (e)=>{
        print();
    if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {//expresion regular evalua navegador
        window.onfocus = function(){window.close();}
    } else {
        window.onafterprint = function(e){
        window.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.

0

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.

Femi
  • 64,273
  • 8
  • 118
  • 148
0

I came up with this simple script:

<script type="text/javascript">
setTimeout(function () { window.print(); }, 500);
setTimeout(function () { window.close(); }, 1000);
</script>
user438383
  • 5,716
  • 8
  • 28
  • 43
0

Close a popup after print.

In the parent windows

  let IframeLink = '../Sale/PriceKOT?SalesID=@(Model.SalesInfo.SalesID)&PrintTypeID=3';
     var newwindow = window.open(IframeLink, "KOT Print", 'width=560,height=550,toolbar=0,menubar=0,location=0');
    if (window.focus) { newwindow.focus() }

    function closeThisPopUp() {            
        newwindow.close();
        printf();
    } 

In the child or popup window

 window.onafterprint = function (event) {
    opener.closeThisPopUp();
    window.close;
};
Arun Prasad E S
  • 9,489
  • 8
  • 74
  • 87