Close window automatically after printing dialog closes

Viewed 223123

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?

40 Answers

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>

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

printWindow.print();
printWindow.onafterprint = () => printWindow.close();

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

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.

<!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

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

jquery:

$(document).ready(function(){ 
  window.print();
  setTimeout(function(){ 
             window.close();
  }, 3000);
});

REF source reference

<script type="text/javascript">
  window.print();
  window.onafterprint = window.close;   
</script>
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.

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

$(function(){
    window.print();
    $("body").hover(function(){
        window.close();
    });
});

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

simple add:

<html>
<body onload="print(); close();">
</body>
</html>

try this:

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

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.

<!--- 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>
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.

I came up with this simple script:

<script type="text/javascript">
setTimeout(function () { window.print(); }, 500);
setTimeout(function () { window.close(); }, 1000);
</script>

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