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?
当用户单击一个按钮时,我将打开一个选项卡。在onload中,我让它打开打印对话框,但是用户问我是否有可能在它发送到打印机打印后,如果选项卡可以自动关闭。我不确定这是否能实现。我尝试过使用setTimeout();,但是这不是一个定义的时间段,因为用户可能会分心,不得不重新打开标签。有什么方法可以做到这一点吗?
24 个解决方案
#1
95
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:
如果您试图在print()调用之后关闭窗口,它可能会立即关闭窗口,而print()将不起作用。这是你不应该做的:
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.
这个解决方案将在Firefox中工作,因为在print()调用中,它将等待打印完成,然后继续处理javascript并关闭窗口()。IE会失败,因为它调用close()函数而不等待print()调用。在打印完成之前,弹出窗口将被关闭。
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.
解决它的一个方法是使用“onafterprint”事件,但我不推荐给你,因为这些事件只在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.
最好的方法是关闭打印对话框后关闭弹出窗口(打印完成或取消)。此时,弹出窗口将被集中,您可以使用“onfocus”事件关闭弹出窗口。
To do this, just insert this javascript embedded code in your popup window:
为此,只需在弹出窗口中插入这个javascript内嵌代码:
<script type="text/javascript">
window.print();
window.onfocus=function(){ window.close();}
</script>
Hope this hepls ;-)
希望这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
对于新的chrome浏览器,它可能仍然关闭得太早。我实现了这个更改,它适用于所有当前的浏览器:2/29/16
setTimeout(function () { window.print(); }, 500);
window.onfocus = function () { setTimeout(function () { window.close(); }, 500); }
#2
62
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);
#3
14
Just:
只是:
window.print();
window.close();
It works.
它的工作原理。
#4
11
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.
我有个问题,IE会在打印对话框出现之前关闭窗口。
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.
这似乎适用于所有浏览器。
#5
10
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,
希望它可以帮助,
#6
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:
使用Chrome我尝试了一段时间来获取windows .onfocus=function() {window.close();以及
。我的结果: …得到焦点=>- I had closed my print dialogue, nothing happened.
- 我结束了我的打印对话,什么也没发生。
- I changed window/tabs in my browser, still nothing.
- 我改变了浏览器的窗口/标签,还是什么都没有。
- changed back to my first window/tab and then the window.onfocus event fired closing the window.
- 更改为我的第一个窗口/选项卡,然后是窗口。onfocus事件触发关闭窗口。
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.
这两个我都没用。所以我使用了一点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>
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.
只需确保包含jquery,然后将其复制/粘贴到正在打印的html中。如果用户已打印、保存为PDF或取消打印作业,窗口/选项卡将自动自毁。注意:我只在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.
正如Jypsy在评论中指出的那样,不需要文档焦点状态。您可以简单地使用noamtcohen的答案,我更改了我的代码,它可以工作。
#7
6
This is a cross-browser solution already tested on Chrome, Firefox, Opera by 2016/05.
这是一个跨浏览器的解决方案,已经在Chrome、Firefox和Opera上测试到2016/05。
Take in mind that Microsoft Edge has a bug that won't close the window if print was cancelled. Related Link
请记住,如果打印被取消,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);
}
}
#8
4
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(); }
}
#9
3
this one works for me:
这个对我很有用:
<script>window.onload= function () { window.print();window.close(); } </script>
#10
3
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.
以下解决方案适用于IE9、IE8、Chrome和FF更新版本(2014-03-10)。场景是这样的:你在一个窗口(a),单击一个按钮/链接启动打印过程,然后一个新窗口(B)的内容印刷打开,立即显示打印对话框,你可以取消或打印,然后是新窗口(B)自动关闭。
The following code allows this. This javascript code is to be placed in the html for window A (not for window 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);
};
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');
#11
2
This works well in Chrome 59:
这在Chrome 59中运行良好:
window.print();
window.onmousemove = function() {
window.close();
}
#12
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.
需要jQuery。可以在_Layout或母版页中完成,以处理所有页面。
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.
这个想法是在URL中传递一个param,告诉页面要打印并关闭,如果设置了param,那么jQuery“ready”事件就会打印出窗口,然后当页面被完全加载(打印后)时,会调用“onload”,它会关闭窗口。所有这些看似额外的步骤都是在关闭窗口之前等待窗口打印出来。
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.
在html主体中,添加和onload事件调用printAndCloseOnLoad()。在本例中,我们使用cshtm,您还可以使用javascript获取param。
<body onload="sccPrintAndCloseOnLoad('@Request.QueryString["PrintAndClose"]');">
In the javascript add the function.
在javascript中添加函数。
function printAndCloseOnLoad(printAndClose) {
if (printAndClose) {
// close self without prompting
window.open('', '_self', ''); window.close();
}
}
And jQuery ready event.
和jQuery事件做好准备。
$(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.
现在,打开任何URL时,只需附加查询字符串param“PrintAndClose=true”,它就会打印并关闭。
#13
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:
这对我很有帮助(2008 /02)。我需要一个独立的请求,因为我的打印文件还没有出现在屏幕上。基于以上一些出色的回答,我注意到:
-
w.onload
must not be set beforew.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 newdocument.write()
then the hook will be called when processing has finished. - w。onload必须在wdocument .write(数据)之前设置。这看起来很奇怪,因为你想事先把钩子钩住。我猜:在没有内容的情况下打开窗口时,钩子已经被点燃了。既然它被点燃了,它就不会再开火了。但是,当新的document.write()仍在处理时,当处理完成时,将调用这个钩子。
-
w.document.close()
still is required. Otherwise nothing happens. - w.document.close()仍然是必需的。否则什么也不会发生。
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.
我在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>
#14
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).
IE有onbeforeprint和onafterprint事件:您可以等待,但它只对IE起作用(可能是也可能不是)。
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.
或者,您可以尝试并等待焦点从打印对话框返回到窗口并关闭它。Amazon Web Services在他们的发票打印对话框中这样做:您点击打印按钮,它将打开打印友好的视图,并立即打开打印机对话框。如果你点击打印或取消打印对话框关闭,那么打印友好的视图会立即关闭。
#15
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.
我最初也想做同样的事情——打开一个为打印设计的新页面,使用JS打印它,然后再次关闭它。这是一个噩梦。
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).
最后,我选择简单地点击到可打印页面,然后使用下面的JS启动一个打印,然后在完成时将自己重定向到我想要的位置(在本例中使用PHP设置了一个变量)。
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).
我已经在OSX和Windows上的Chrome和Firefox上测试过了,IE11-8也适用于所有的浏览器(尽管如果你没有安装打印机的话,IE8会冻结一段时间)。
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>
#16
0
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.
这对于我将HTML注入到弹出窗口中效果最好,例如
https://*.com/a/11782214/1322092
https://*.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>';
#17
0
just use this java 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();
}
it will close window after submit or cancel button click
提交或取消按钮点击后将关闭窗口
#18
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:
在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>
#19
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".
这在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);
#20
0
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();
#21
0
setTimeout(function () { window.print(); }, 500);
window.onfocus = function () { setTimeout(function () { window.close(); }, 500); }
It's work perfectly for me. Hope it helps
这对我来说是完美的。希望它能帮助
#22
0
This works for me on Chrome (haven't tried on others)
这对我来说在Chrome上很有用(没试过)
$(function(){
window.print();
$("body").hover(function(){
window.close();
});
});
#23
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();
#24
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):
我认为最好的方法是等待文档(即DOM)正确加载,然后使用print和close函数。我在文档准备函数(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):
值得注意的是,上面的内容放在我的“可打印页面”(您可以将其称为“可打印页面”)上。我从另一个页面链接到的html(称为linkpage)。html如果你想):
<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
所以它会
- Open a new window when you click Print
- 单击“打印”时打开一个新窗口
- Trigger the (browser) print dialogue after page load
- 在页面加载之后触发(浏览器)打印对话
- Close window after printed (or cancelled).
- 打印(或取消)后关闭窗口。
Hope you are having fun!
希望你玩得开心!
#1
95
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:
如果您试图在print()调用之后关闭窗口,它可能会立即关闭窗口,而print()将不起作用。这是你不应该做的:
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.
这个解决方案将在Firefox中工作,因为在print()调用中,它将等待打印完成,然后继续处理javascript并关闭窗口()。IE会失败,因为它调用close()函数而不等待print()调用。在打印完成之前,弹出窗口将被关闭。
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.
解决它的一个方法是使用“onafterprint”事件,但我不推荐给你,因为这些事件只在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.
最好的方法是关闭打印对话框后关闭弹出窗口(打印完成或取消)。此时,弹出窗口将被集中,您可以使用“onfocus”事件关闭弹出窗口。
To do this, just insert this javascript embedded code in your popup window:
为此,只需在弹出窗口中插入这个javascript内嵌代码:
<script type="text/javascript">
window.print();
window.onfocus=function(){ window.close();}
</script>
Hope this hepls ;-)
希望这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
对于新的chrome浏览器,它可能仍然关闭得太早。我实现了这个更改,它适用于所有当前的浏览器:2/29/16
setTimeout(function () { window.print(); }, 500);
window.onfocus = function () { setTimeout(function () { window.close(); }, 500); }
#2
62
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);
#3
14
Just:
只是:
window.print();
window.close();
It works.
它的工作原理。
#4
11
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.
我有个问题,IE会在打印对话框出现之前关闭窗口。
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.
这似乎适用于所有浏览器。
#5
10
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,
希望它可以帮助,
#6
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:
使用Chrome我尝试了一段时间来获取windows .onfocus=function() {window.close();以及
。我的结果: …得到焦点=>- I had closed my print dialogue, nothing happened.
- 我结束了我的打印对话,什么也没发生。
- I changed window/tabs in my browser, still nothing.
- 我改变了浏览器的窗口/标签,还是什么都没有。
- changed back to my first window/tab and then the window.onfocus event fired closing the window.
- 更改为我的第一个窗口/选项卡,然后是窗口。onfocus事件触发关闭窗口。
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.
这两个我都没用。所以我使用了一点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>
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.
只需确保包含jquery,然后将其复制/粘贴到正在打印的html中。如果用户已打印、保存为PDF或取消打印作业,窗口/选项卡将自动自毁。注意:我只在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.
正如Jypsy在评论中指出的那样,不需要文档焦点状态。您可以简单地使用noamtcohen的答案,我更改了我的代码,它可以工作。
#7
6
This is a cross-browser solution already tested on Chrome, Firefox, Opera by 2016/05.
这是一个跨浏览器的解决方案,已经在Chrome、Firefox和Opera上测试到2016/05。
Take in mind that Microsoft Edge has a bug that won't close the window if print was cancelled. Related Link
请记住,如果打印被取消,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);
}
}
#8
4
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(); }
}
#9
3
this one works for me:
这个对我很有用:
<script>window.onload= function () { window.print();window.close(); } </script>
#10
3
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.
以下解决方案适用于IE9、IE8、Chrome和FF更新版本(2014-03-10)。场景是这样的:你在一个窗口(a),单击一个按钮/链接启动打印过程,然后一个新窗口(B)的内容印刷打开,立即显示打印对话框,你可以取消或打印,然后是新窗口(B)自动关闭。
The following code allows this. This javascript code is to be placed in the html for window A (not for window 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);
};
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');
#11
2
This works well in Chrome 59:
这在Chrome 59中运行良好:
window.print();
window.onmousemove = function() {
window.close();
}
#12
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.
需要jQuery。可以在_Layout或母版页中完成,以处理所有页面。
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.
这个想法是在URL中传递一个param,告诉页面要打印并关闭,如果设置了param,那么jQuery“ready”事件就会打印出窗口,然后当页面被完全加载(打印后)时,会调用“onload”,它会关闭窗口。所有这些看似额外的步骤都是在关闭窗口之前等待窗口打印出来。
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.
在html主体中,添加和onload事件调用printAndCloseOnLoad()。在本例中,我们使用cshtm,您还可以使用javascript获取param。
<body onload="sccPrintAndCloseOnLoad('@Request.QueryString["PrintAndClose"]');">
In the javascript add the function.
在javascript中添加函数。
function printAndCloseOnLoad(printAndClose) {
if (printAndClose) {
// close self without prompting
window.open('', '_self', ''); window.close();
}
}
And jQuery ready event.
和jQuery事件做好准备。
$(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.
现在,打开任何URL时,只需附加查询字符串param“PrintAndClose=true”,它就会打印并关闭。
#13
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:
这对我很有帮助(2008 /02)。我需要一个独立的请求,因为我的打印文件还没有出现在屏幕上。基于以上一些出色的回答,我注意到:
-
w.onload
must not be set beforew.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 newdocument.write()
then the hook will be called when processing has finished. - w。onload必须在wdocument .write(数据)之前设置。这看起来很奇怪,因为你想事先把钩子钩住。我猜:在没有内容的情况下打开窗口时,钩子已经被点燃了。既然它被点燃了,它就不会再开火了。但是,当新的document.write()仍在处理时,当处理完成时,将调用这个钩子。
-
w.document.close()
still is required. Otherwise nothing happens. - w.document.close()仍然是必需的。否则什么也不会发生。
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.
我在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>
#14
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).
IE有onbeforeprint和onafterprint事件:您可以等待,但它只对IE起作用(可能是也可能不是)。
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.
或者,您可以尝试并等待焦点从打印对话框返回到窗口并关闭它。Amazon Web Services在他们的发票打印对话框中这样做:您点击打印按钮,它将打开打印友好的视图,并立即打开打印机对话框。如果你点击打印或取消打印对话框关闭,那么打印友好的视图会立即关闭。
#15
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.
我最初也想做同样的事情——打开一个为打印设计的新页面,使用JS打印它,然后再次关闭它。这是一个噩梦。
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).
最后,我选择简单地点击到可打印页面,然后使用下面的JS启动一个打印,然后在完成时将自己重定向到我想要的位置(在本例中使用PHP设置了一个变量)。
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).
我已经在OSX和Windows上的Chrome和Firefox上测试过了,IE11-8也适用于所有的浏览器(尽管如果你没有安装打印机的话,IE8会冻结一段时间)。
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>
#16
0
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.
这对于我将HTML注入到弹出窗口中效果最好,例如
https://*.com/a/11782214/1322092
https://*.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>';
#17
0
just use this java 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();
}
it will close window after submit or cancel button click
提交或取消按钮点击后将关闭窗口
#18
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:
在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>
#19
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".
这在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);
#20
0
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();
#21
0
setTimeout(function () { window.print(); }, 500);
window.onfocus = function () { setTimeout(function () { window.close(); }, 500); }
It's work perfectly for me. Hope it helps
这对我来说是完美的。希望它能帮助
#22
0
This works for me on Chrome (haven't tried on others)
这对我来说在Chrome上很有用(没试过)
$(function(){
window.print();
$("body").hover(function(){
window.close();
});
});
#23
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();
#24
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):
我认为最好的方法是等待文档(即DOM)正确加载,然后使用print和close函数。我在文档准备函数(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):
值得注意的是,上面的内容放在我的“可打印页面”(您可以将其称为“可打印页面”)上。我从另一个页面链接到的html(称为linkpage)。html如果你想):
<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
所以它会
- Open a new window when you click Print
- 单击“打印”时打开一个新窗口
- Trigger the (browser) print dialogue after page load
- 在页面加载之后触发(浏览器)打印对话
- Close window after printed (or cancelled).
- 打印(或取消)后关闭窗口。
Hope you are having fun!
希望你玩得开心!