인쇄 대화 상자가 닫힌 후 자동으로 창 닫기
사용자가 버튼을 클릭하면 탭이 열립니다. 온 onload
나는 그것이 인쇄 대화 상자를 불러 가지고 있지만, 사용자는 탭 자체를 닫을 수 있다면 프린터로 전송 한 후에는, 인쇄 가능성 여부를 나에게 물었다. 이것이 가능한지 잘 모르겠습니다. 을 사용해 보았지만 setTimeout();
사용자가주의를 산만하게하고 탭을 다시 열어야하기 때문에 정의 된 기간이 아닙니다. 이를 수행 할 방법이 있습니까?
print () 호출 직후 창을 닫으려고하면 즉시 창을 닫고 print ()가 작동하지 않을 수 있습니다. 이것은 당신이하지 말아야 할 것입니다 :
window.open();
...
window.print();
window.close();
이 솔루션은 Firefox에서 작동합니다. print () 호출시 인쇄가 완료 될 때까지 기다린 다음 javascript 처리를 계속하고 창을 닫습니다 (). IE는 print () 호출이 완료 될 때까지 기다리지 않고 close () 함수를 호출하므로 실패합니다. 인쇄가 완료되기 전에 팝업 창이 닫힙니다.
이를 해결하는 한 가지 방법은 "onafterprint"이벤트를 사용하는 것이지만 이러한 이벤트는 IE에서만 작동하므로 권장하지 않습니다.
가장 좋은 방법 은 인쇄 대화 상자가 닫히면 (인쇄가 완료되거나 취소됨) 팝업 창을 닫는 것 입니다. 이때 팝업 창에 초점이 맞춰지고 "onfocus"이벤트를 사용하여 팝업을 닫을 수 있습니다.
이렇게하려면 팝업 창에 다음 자바 스크립트 포함 코드를 삽입하면됩니다.
<script type="text/javascript">
window.print();
window.onfocus=function(){ window.close();}
</script>
희망이 hepls ;-)
최신 정보:
새 크롬 브라우저의 경우 너무 빨리 닫힐 수 있습니다 . 여기를 참조하십시오 . 이 변경 사항을 구현했으며 현재 모든 브라우저에서 작동합니다 : 2/29/16
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에서 이미 테스트 된 브라우저 간 솔루션 입니다.
마음에 받아 마이크로 소프트 엣지 버그가 인쇄가 취소 된 경우 창을 닫으하지 않습니다. 관련 링크
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);
}
}
얻가하면서 크롬 내가 재판을 사용 window.onfocus=function() { window.close(); }
하고이 <body ... onfocus="window.close()">
작업에. 내 결과 :
- 인쇄 대화를 닫았지만 아무 일도 일어나지 않았습니다.
- 내 브라우저에서 창 / 탭을 변경했지만 여전히 아무것도 없습니다.
- 내 첫 번째 창 / 탭으로 다시 변경된 다음 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로 저장하거나 인쇄 작업을 취소 한 경우 창 / 탭이 자동으로 자동 삭제됩니다. 참고 : 나는 이것을 크롬에서만 테스트했습니다.
편집하다
Jypsy가 주석에서 지적했듯이 문서 포커스 상태는 필요하지 않습니다. noamtcohen의 답변을 간단히 사용할 수 있으며 코드를 변경하여 작동합니다.
다음은 나를 위해 일했습니다.
function print_link(link) {
var mywindow = window.open(link, 'title', 'height=500,width=500');
mywindow.onload = function() { mywindow.print(); mywindow.close(); }
}
이것은 나를 위해 작동합니다.
<script>window.onload= function () { window.print();window.close(); } </script>
다음 솔루션은 2014 년 3 월 10 일 기준 IE9, IE8, Chrome 및 FF 최신 버전에서 작동합니다. 시나리오는 다음과 같습니다 : 현재 창 (A)에서 버튼 / 링크를 클릭하여 인쇄 프로세스를 시작하면 인쇄 할 내용이있는 새 창 (B)이 열리고 인쇄 대화 상자가 즉시 표시됩니다. 취소하거나 인쇄하면 새 창 (B)이 자동으로 닫힙니다.
다음 코드는이를 허용합니다. 이 자바 스크립트 코드는 창 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');
이것은 Chrome 59에서 잘 작동합니다.
window.print();
window.onmousemove = function() {
window.close();
}
다음을 수행하면 쉽게 해결할 수 있습니다.
<script type="text/javascript">
window.print();
window.onafterprint = window.close;
</script>
이것은 <body onload="window.print()"...
IE, Chrome 및 FF (Mac)에서 작동하지만 Windows에서는 FF 와 같은 팝업에 HTML을 삽입하는 데 가장 적합했습니다 .
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" 창을 닫는 호출됩니다. 이 모든 추가 단계는 창이 자동으로 닫히기 전에 인쇄 될 때까지 기다리는 것입니다.
html 본문에서 printAndCloseOnLoad ()를 호출하는 이벤트 추가 및 onload. 이 예제에서 우리는 cshtm을 사용하고 있으며, 매개 변수를 얻기 위해 자바 스크립트를 사용할 수도 있습니다.
<body onload="sccPrintAndCloseOnLoad('@Request.QueryString["PrintAndClose"]');">
자바 스크립트에서 함수를 추가하십시오.
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"를 추가하면 인쇄되고 닫힙니다.
이것이 나를 위해 일한 것입니다 (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 솔루션이 있습니다.
<!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 및 자바 스크립트로 새 탭 창을 인쇄하고 닫습니다.
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>
이 자바 스크립트를 사용하십시오.
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);
나에게 내 최종 솔루션은 여러 가지 답변의 혼합이었습니다.
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();
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();
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):
<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):
<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!
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();
}
}
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();
}"
참고URL : https://stackoverflow.com/questions/6460630/close-window-automatically-after-printing-dialog-closes
'code' 카테고리의 다른 글
종횡비를 계산하는 알고리즘은 무엇입니까? (0) | 2020.10.25 |
---|---|
패키지 이름을 알고 애플리케이션 시작 (0) | 2020.10.25 |
Alembic 업그레이드 스크립트에서 삽입 및 업데이트를 어떻게 실행합니까? (0) | 2020.10.24 |
정수 부동 소수점 자체가 1.f로 보장됩니까? (0) | 2020.10.24 |
분기 전략 (0) | 2020.10.24 |