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

问题描述 投票:68回答:30

当用户单击按钮时,我打开了一个标签。在onload上,我打开了打印对话框,但是用户问我是否有可能在它发送到打印机后进行打印,如果标签可以自行关闭。我不确定是否可以这样做。我尝试过使用setTimeout();,但由于用户可能会分心而不得不重新打开选项卡,因此它不是一段定义的时间。有没有办法实现这个目标?

javascript printing
30个回答
103
投票

如果您尝试在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浏览器,它可能仍然关闭太快see here。我已实现此更改,它适用于所有当前浏览器:2/29/16

        setTimeout(function () { window.print(); }, 500);
        window.onfocus = function () { setTimeout(function () { window.close(); }, 500); }

3
投票

从2014-03-10开始,以下解决方案适用于IE9,IE8,Chrome和FF新版本。场景是这样的:你在一个窗口(A)中,你点击一个按钮/链接来启动打印过程,然后打开一个新窗口(B),打开要打印的内容,立即显示打印对话框,您可以取消或打印,然后新窗口(B)自动关闭。

以下代码允许这样做。这个javascript代码将被放置在窗口A的html中(不适用于窗口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);
};

启动进程的按钮/链接只需调用此函数,如:

openPrintWindow('http://www.google.com', 'windowTitle', 'width=820,height=600');

3
投票

这适用于Chrome 59:

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

2
投票

当然,这可以通过以下方式轻松解决:

  <script type="text/javascript">
     window.print();
     window.onafterprint = window.close;
  </script>

1
投票

这最适合我将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>';

1
投票

这就是我做的......

启用窗口以根据查询参数打印和关闭自身。

需要jQuery。可以在_Layout或母版页中完成,以便与所有页面一起使用。

想法是在URL中传递一个参数,告诉页面打印和关闭,如果设置了参数,则jQuery“ready”事件打印窗口,然后当页面完全加载(打印后)“onload”调用它关闭窗口。所有这些看似额外的步骤都是在关闭之前等待窗口打印。

在调用printAndCloseOnLoad()的html body add和onload事件中。在这个例子中我们使用cshtm,你也可以使用javascript来获取param。

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

在javascript中添加功能。

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

和jQuery准备好的事件。

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

现在打开任何URL时,只需附加查询字符串参数“PrintAndClose = true”,它就会打印并关闭。


1
投票

这对我有用(2018/02)。我需要一个单独的请求,因为我的打印还没有在屏幕上。基于上面的一些优秀回答,我感谢大家,我注意到:

  • w.onload不得在w.document.write(data)之前设置。 这看起来很奇怪,因为你想要预先设置钩子。我的猜测:当没有内容打开窗口时,钩子已经被解雇了。由于它被解雇了,它不会再次开火。但是,当仍有一个新的document.write()处理时,那么当处理完成时将调用钩子。
  • w.document.close()仍然是必需的。否则没有任何反应

我在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>

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

这是我的ES2016解决方案。


1
投票
<!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打印并关闭新的选项卡窗口


0
投票

IE有(有?)onbeforeprintonafterprint事件:你可以等待,但它只适用于IE(可能或可能没有)。

或者,您可以尝试等待焦点从打印对话框返回到窗口并关闭它。 Amazon Web Services在其发票打印对话框中执行此操作:您点击打印按钮,它打开了打印友好视图并立即打开打印机对话框。如果您点击打印或取消打印对话框关闭,则打印友好视图会立即关闭。


0
投票

让这样的东西跨浏览器工作有很多痛苦。

我原本打算做同样的事情 - 打开一个用于打印的新页面,用JS打印它,然后再关闭它。这是一场噩梦。

最后,我选择只需点击进入可打印页面,然后使用下面的JS启动打印,然后将自己重定向到我想要完成的位置(在本例中使用PHP设置变量)。

我已经在OSX和Windows以及IE11-8上对Chrome和Firefox进行了测试,它适用于所有(如果你实际上没有安装打印机,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>

71
投票

这就是我想出来的,我不知道为什么在关闭之前会有一点延迟。

 window.print();
 setTimeout(window.close, 0);

0
投票

只需使用此JavaScript

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

它会在提交或取消按钮点击后关闭窗口


0
投票

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

0
投票

这适用于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);

0
投票

对我来说,我的最终解决方案是几个答案的组合:

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

0
投票
setTimeout(function () { window.print(); }, 500);
        window.onfocus = function () { setTimeout(function () { window.close(); }, 500); }

这对我来说很完美。希望能帮助到你


0
投票

这对我在Chrome上有用(没有尝试过其他人)

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

0
投票

我试过这个并且它有效

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

0
投票

我想最好的方法是等待文档(aka 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>

所以它会

  1. 单击“打印”时打开一个新窗口
  2. 页面加载后触发(浏览器)打印对话框
  3. 打印(或取消)后关闭窗口。

希望你玩得开心!


0
投票

简单添加:

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

0
投票

试试这个:

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

14
投票

只是:

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

有用。


0
投票

这对我来说非常适合@holger,但是,我修改了它并且更适合我,窗口现在弹出并立即关闭你打印或取消按钮。

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

12
投票

我只想写我已经做过的事情以及对我有用的事情(因为我尝试过的其他事情都没有)。

我遇到的问题是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();

这似乎适用于所有浏览器。


10
投票

这段代码非常适合我:

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

当页面打开时,它会自动打开打印对话框,打印或取消后会关闭窗口。

希望能帮助到你,


7
投票

使用Chrome我尝试了一段时间让window.onfocus=function() { window.close(); }<body ... onfocus="window.close()">工作。我的结果:

  1. 我关闭了我的打印对话,没有任何反应。
  2. 我在浏览器中更改了窗口/标签,但仍然没有。
  3. 更改回我的第一个窗口/选项卡,然后关闭窗口触发window.onfocus事件。

我还尝试了<body onload="window.print(); window.close()" >,导致窗口关闭,然后我甚至可以点击打印对话框中的任何内容。

我无法使用其中任何一个。所以我使用了一个小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的答案,我将我的代码更改为该代码并且它可以正常工作。


7
投票

这是一款已在2016/05年度在Chrome,Firefox,Opera上测试过的跨浏览器解决方案。

请记住,Microsoft Edge有一个错误,如果打印被取消,它将无法关闭窗口。 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);
    }
}

5
投票

以下对我有用:

function print_link(link) {
    var mywindow = window.open(link, 'title', 'height=500,width=500');   
    mywindow.onload = function() { mywindow.print(); mywindow.close(); }
}

3
投票

这个对我有用:

<script>window.onload= function () { window.print();window.close();   }  </script>
© www.soinside.com 2019 - 2024. All rights reserved.