打印对话框关闭后自动关闭窗口

| 用户单击按钮时,我会打开一个选项卡。在“ 0”上,我调出打印对话框,但是用户问我,是否有可能在将标签发送到打印机后关闭标签。我不确定是否可以做到。我曾尝试使用
setTimeout();
,但这不是定义的时间段,因为用户可能会分心并不得不重新打开该选项卡。有什么办法可以做到这一点?     
已邀请:
        如果您尝试在调用print()之后立即关闭窗口,则它可能会立即关闭窗口,而print()将不起作用。这是您不应该做的:
window.open();
...
window.print();
window.close();
此解决方案将在Firefox中运行,因为在调用print()时,它将等待直到完成打印,然后继续处理javascript并关闭窗口。 IE会失败,因为它调用了close()函数而没有等待print()调用完成。在完成打印之前,弹出窗口将关闭。 解决此问题的一种方法是使用“ onafterprint”事件,但我不建议您这样做,因为这些事件仅在IE中有效。 最好的方法是在关闭打印对话框(打印完成或取消)后关闭弹出窗口。此时,弹出窗口将被聚焦,您可以使用\“ onfocus \”事件关闭弹出窗口。 为此,只需在弹出窗口中插入以下javascript嵌入式代码:
<script type=\"text/javascript\">
window.print();
window.onfocus=function(){ window.close();}
</script>
希望这个帮助;-) 更新: 对于新的Chrome浏览器,它可能仍会关闭太快,请参见此处。我已经实现了此更改,它适用于所有当前浏览器:16/2/29 /
        setTimeout(function () { window.print(); }, 500);
        window.onfocus = function () { setTimeout(function () { window.close(); }, 500); }
    
        这是我想出的,我不知道为什么在关闭之前会有一个小的延迟。
 window.print();
 setTimeout(window.close, 0);
    
        只是:
window.print();
window.close();
有用。     
        我只想写自己的工作和对我有用的东西(因为我尝试过的其他东西都没有奏效)。 我有一个问题,即IE在打印对话框启动之前会关闭窗口。 经过大量的反复试验和测试之后,这就是我要做的工作:
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();
这似乎适用于所有浏览器。     
        这段代码非常适合我:
<body onload=\"window.print()\" onfocus=\"window.close()\">
当页面打开时,它会自动打开打印对话框,在打印或取消后,它会关闭窗口。 希望能帮助到你,     
        这是一个跨浏览器解决方案,已在2016/05年前在Chrome,Firefox,Opera上进行了测试。 请记住,Microsoft Edge有一个错误,如果取消打印,该错误不会关闭窗口。相关链接
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);
    }
}
    
        我尝试使用Chrome一段时间以获得
window.onfocus=function() { window.close(); }
<body ... onfocus=\"window.close()\">
去工作。我的结果: 我已经关闭了打印对话,没有任何反应。 我在浏览器中更改了窗口/标签,仍然没有任何改变。 更改回我的第一个窗口/选项卡,然后触发window.onfocus事件以关闭窗口。 我还尝试了“ 12”,这导致窗口关闭,甚至无法在打印对话框中单击任何内容。 我不能使用其中任何一个。 因此,我使用了一个小Jquery来监视文档状态,并且此代码对我有用。
<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>
只需确保已包含jquery,然后将其复制/粘贴到要打印的html中即可。如果用户已打印,另存为PDF或取消了打印作业,则窗口/选项卡将自动自毁。注意:我只在chrome中测试过此功能。 编辑 正如Jypsy在评论中指出的那样,不需要文档焦点状态。您可以简单地使用noamtcohen的答案,我将代码更改为该代码即可。     
        这对我有用:
<script>window.onload= function () { window.print();window.close();   }  </script>
    
        以下为我工作:
function print_link(link) {
    var mywindow = window.open(link, \'title\', \'height=500,width=500\');   
    mywindow.onload = function() { mywindow.print(); mywindow.close(); }
}
    
        确保这样做很容易解决:
  <script type=\"text/javascript\">
     window.print();
     window.onafterprint = window.close();
  </script>
    
        这在Chrome 59中效果很好:
window.print();
window.onmousemove = function() {
  window.close();
}
    
        自2014年3月10日起,以下解决方案适用于IE9,IE8,Chrome和FF的较新版本。 场景是这样的:您在窗口(A)中,单击按钮/链接以启动打印过程,然后打开一个包含要打印内容的新窗口(B),立即显示打印对话框,您可以取消或打印,然后新窗口(B)自动关闭。 以下代码允许这样做。此javascript代码将放在窗口A(而不是窗口B)的html中:
/**
 * 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);
};
启动该过程的按钮/链接只需调用此函数,如下所示:
openPrintWindow(\'http://www.google.com\', \'windowTitle\', \'width=820,height=600\');
    
        
<!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>
单击并使用php和javascript打印并关闭新的选项卡窗口     
这对将HTML注入弹出窗口(如
<body onload=\"window.print()\"...
)中的效果最好 上面的方法适用于IE,Chrome和FF(在Mac上),但在Windows上则没有FF。 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>\';
    
        这是我的工作... 启用窗口以根据查询参数打印并自行关闭。 需要jQuery。可以在_Layout或母版页中完成以处理所有页面。 这个想法是在URL中传递一个告诉页面要打印和关闭的参数,如果设置了该参数,则jQuery“ ready”事件将打印该窗口,然后在页面完全加载(打印后)时“ onload”被称为关闭窗口。所有这些看似多余的步骤都是在关闭窗口之前等待窗口打印。 在html主体中,添加和加载事件调用printAndCloseOnLoad()。在此示例中,我们使用的是cshtm,也可以使用javascript获取参数。
<body onload=\"sccPrintAndCloseOnLoad(\'@Request.QueryString[\"PrintAndClose\"]\');\">
在javascript中添加函数。
function printAndCloseOnLoad(printAndClose) {
    if (printAndClose) {
        // close self without prompting
        window.open(\'\', \'_self\', \'\'); window.close();
    }
}
和jQuery ready事件。
$(document).ready(function () {
    if (window.location.search.indexOf(\"PrintAndClose=\") > 0)
        print();
});
现在,当打开任何URL时,只需附加查询字符串参数“ PrintAndClose = true”,它将打印并关闭。     

bab

        对我来说,我的最终解决方案是以下几种答案的组合:
    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();
    
        这是对我有用的(2018/02)。我需要一个单独的请求,因为我的打印尚未显示在屏幕上。 基于以上一些出色的回应,我感谢大家,我注意到: 不得在
w.document.write(data)
之前设定27ѭ。 似乎很奇怪,因为您想预先设置钩子。我的猜测:当打开没有内容的窗口时,挂钩已经被触发。由于它已被发射,因此不会再次发射。但是,当仍然有新的ѭ29进行处理时,则在处理完成后将调用该挂钩。 仍需要30英镑。否则什么也不会发生。 我已经在Chrome 64.0,IE11(11.248),Edge 41.16299(edgeHTML 16.16299),FF 58.0.1中对此进行了测试。 他们会抱怨弹出窗口,但会打印出来。
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>
    
        
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();
};
这是我的ES2016解决方案。     
        只需通过onafterprint事件处理程序包装window.close,它对我有用
printWindow.print();
printWindow.onafterprint = () => printWindow.close();
    
        IE曾经(有?)the35ѭ和
onafterprint
事件:您可以等待,但是它仅适用于IE(可能会也可能不会)。 或者,您可以尝试等待焦点从打印对话框返回到窗口并关闭它。 Amazon Web Services在其发票打印对话框中执行此操作:按下“打印”按钮,它将打开易于打印的视图,并立即打开打印机对话框。如果您点击打印或取消打印,则打印对话框关闭,然后适合打印的视图立即关闭。     
        使这样的东西跨浏览器工作非常痛苦。 我本来希望做同样的事情-打开一个样式为打印的新页面,使用JS打印,然后再次关闭。这是一场噩梦。 最后,我选择了简单地单击到可打印页面,然后使用下面的JS来启动打印,然后将自己重定向到完成后想要去的地方(在这种情况下,在PHP中设置了变量)。 我已经在OSX和Windows的Chrome和Firefox以及IE11-8上对此进行了测试,并且可以在所有设备上使用(尽管如果您实际上未安装打印机,IE8会冻结一段时间)。 狩猎愉快(打印)。
<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>
    
        只需使用此Java脚本
 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();
}
单击提交或取消按钮后,它将关闭窗口     
        在IE11上,两次调用onfocus事件,因此两次提示用户关闭窗口。可以通过稍作更改来防止这种情况:
<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>
    
        在FF 36,Chrome 41和IE 11中,这对我有用。即使您取消了打印,甚至用右上角的“ 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);
    
        
setTimeout(function () { window.print(); }, 500);
        window.onfocus = function () { setTimeout(function () { window.close(); }, 500); }
这对我来说是完美的。 希望能帮助到你     
        这对我在Chrome上有效(还没有尝试过其他功能)
$(function(){
    window.print();
    $(\"body\").hover(function(){
        window.close();
    });
});
    
        我尝试了这个并且有效
var popupWin = window.open(\'\', \'PrintWindow\', 
\'width=650,height=650,location=no,left=200px\');
popupWin.document.write(data[0].xmldata);
popupWin.print();
popupWin.close();
    
我猜最好的方法是等待文档(即DOM)正确加载,然后使用打印和关闭功能。我将其包装在Document Ready函数(jQuery)中:
<script>
$(document).ready(function () {
window.print();
window.close();
});
</script>
值得注意的是,以上内容放在我的“可打印页面”上(您可以将其称为我从另一个页面链接到的“ printable.html \”(如果需要,可以将其称为linkpage.html):
<script>
function openNewPrintWindow(){
var newWindow=window.open(\'http://printable.html\'); //replace with your url
newWindow.focus(); //Sets focus window
}
</script>
对于只寻找解决方案的复制粘贴开发人员,以下是上述功能的“触发器”(同一页):
<button onclick=\"openNewPrintWindow()\">Print</button>
所以会 单击打印时打开一个新窗口 页面加载后触发(浏览器)打印对话框 打印(或取消)后关闭窗口。 希望你玩得开心!     
        简单添加:
<html>
<body onload=\"print(); close();\">
</body>
</html>
    
        尝试这个:
var xxx = window.open(\"\",\"Printing...\");
xxx.onload = function () {
     setTimeout(function(){xxx.print();}, 500);
     xxx.onfocus = function () {
        xxx.close();
     }  
}
    

要回复问题请先登录注册