【发布时间】:2011-09-21 14:00:21
【问题描述】:
当用户单击按钮时,我打开了一个选项卡。在onload 上,我打开了打印对话框,但用户问我是否有可能在它发送到打印机进行打印后,如果选项卡可以自行关闭。我不确定这是否可以做到。我尝试过使用setTimeout();,但这不是一个定义的时间段,因为用户可能会分心并不得不重新打开选项卡。有没有办法做到这一点?
【问题讨论】:
标签: javascript printing
当用户单击按钮时,我打开了一个选项卡。在onload 上,我打开了打印对话框,但用户问我是否有可能在它发送到打印机进行打印后,如果选项卡可以自行关闭。我不确定这是否可以做到。我尝试过使用setTimeout();,但这不是一个定义的时间段,因为用户可能会分心并不得不重新打开选项卡。有没有办法做到这一点?
【问题讨论】:
标签: javascript printing
如果您尝试在 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); }
【讨论】:
window.onload = function () { window.print(); setTimeout(window.close, 500); };
这是我想出来的,不知道为什么在关闭之前会有一点延迟。
window.print();
setTimeout(window.close, 0);
【讨论】:
这样做很容易解决这个问题:
<script type="text/javascript">
window.onafterprint = window.close;
window.print();
</script>
或者,如果您想做一些事情,例如转到上一页。
<script type="text/javascript">
window.print();
window.onafterprint = back;
function back() {
window.history.back();
}
</script>
【讨论】:
window.onafterprint = window.close();应该是window.onafterprint = window.close; 前者将window.close()的结果赋值给onafterprint。这将导致window.close() 在设置处理程序时立即运行,并且在引发onafterprint 事件时不运行任何内容。后者将window.close 分配为事件处理程序,这正是我们想要的。
window.print(); 之后暂停,直到打印对话框被关闭。发生这种情况时,onafterprint 事件可能会在分配 onafterprint 之前引发。因此,window.onafterprint = window.close; 最好位于window.print(); 之前。否则,此答案中使用的方法比其他答案建议的基于 onfocus 或 setTimeout 的方法效果更好。
只是:
window.print();
window.close();
有效。
【讨论】:
Scripts may close only the windows that were opened by it. 警告。
window.onafterprint = function(){ 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()">
页面打开时会自动打开打印对话框,打印或取消后会关闭窗口。
希望对你有帮助,
【讨论】:
只需通过 onafterprint 事件处理程序包装 window.close,它对我有用
printWindow.print();
printWindow.onafterprint = () => printWindow.close();
【讨论】:
这是一个跨浏览器解决方案已在 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);
}
}
【讨论】:
我尝试使用 Chrome 获取 window.onfocus=function() { window.close(); } 和
<body ... onfocus="window.close()">
去工作。我的结果:
我还尝试了<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 在 cmets 中指出的那样,不需要文档焦点状态。您可以简单地使用 noamtcohen 的答案,我将代码更改为它并且它可以工作。
【讨论】:
这在 Chrome 59 中运行良好:
window.print();
window.onmousemove = function() {
window.close();
}
【讨论】:
这对我有用 11/2020 <body onafterprint="window.close()"> ... 很简单。
【讨论】:
这个对我有用:
<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(); }
}
【讨论】:
我尝试了很多没有用的方法。 唯一对我有用的是:
window.print();
window.onafterprint = function () {
window.close();
}
在 chrome 上测试。
【讨论】:
以下解决方案适用于 2014 年 3 月 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');
【讨论】:
<!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 打印和关闭新标签窗口,单击按钮
【讨论】:
jquery:
$(document).ready(function(){
window.print();
setTimeout(function(){
window.close();
}, 3000);
});
【讨论】:
这最适合我将 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 “就绪”事件会打印窗口,然后当页面完全加载(打印后)调用“onload”来关闭窗口。所有这些看似额外的步骤都是在关闭之前等待窗口打印。
在调用 printAndCloseOnLoad() 的 html 正文中添加和 onload 事件。在这个例子中我们使用的是 cshtm,你也可以使用 javascript 来获取参数。
<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”,它就会打印并关闭。
【讨论】:
对我来说,我的最终解决方案是几个答案的混合:
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.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>
【讨论】:
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 解决方案。
【讨论】:
这对我来说非常适合@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();
}"
【讨论】:
IE 有(有?)onbeforeprint 和 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();
});
});
【讨论】: