window.print() 마감을 탐지하는 방법
애플리케이션에서 사용자를 위한 바우처 페이지를 다음과 같이 출력하려고 했습니다.
var htm ="<div>Voucher Details</div>";
$('#divprint').html(htm);
window.setTimeout('window.print()',2000);
'divprint입니다.div바우처에 대한 정보를 저장하는 내 페이지에서.
작동하고 인쇄 페이지가 나타납니다.가 '어플리케이션'을앱을 .print또는 'close브라우저의 팝업 인쇄 대화 상자에 표시됩니다.
예를 들어 팝업 창이 닫힌 후 사용자를 다른 페이지로 리디렉션하려고 합니다.
window.application.directtoantherpage();//a function which direct user to other page
팝업 인쇄 창이 닫히거나 인쇄가 완료되었는지 확인하려면 어떻게 해야 합니까?
Afterprint 이벤트를 들을 수 있습니다.
https://developer.mozilla.org/en-US/docs/Web/API/window.onafterprint
window.onafterprint = function(){
console.log("Printing completed...");
}
다른 방법으로 window.matchMedia를 사용하여 이 기능을 얻을 수도 있습니다.
(function() {
var beforePrint = function() {
console.log('Functionality to run before printing.');
};
var afterPrint = function() {
console.log('Functionality to run after printing');
};
if (window.matchMedia) {
var mediaQueryList = window.matchMedia('print');
mediaQueryList.addListener(function(mql) {
if (mql.matches) {
beforePrint();
} else {
afterPrint();
}
});
}
window.onbeforeprint = beforePrint;
window.onafterprint = afterPrint;
}());
출처: http://tjvantoll.com/2012/06/15/detecting-print-requests-with-javascript/
크롬(V.35.0.1916.153m)에서 다음을 시도합니다.
function loadPrint() {
window.print();
setTimeout(function () { window.close(); }, 100);
}
저한테 잘 어울려요.사용자가 인쇄 대화 상자 작업을 마치면 창이 닫힙니다.
크롬, 익스플로러, 익스플로러, 인터넷 익스플로러와 호환 가능
참고: jQuery가 필요합니다.
<script>
window.onafterprint = function(e){
$(window).off('mousemove', window.onafterprint);
console.log('Print Dialog Closed..');
};
window.print();
setTimeout(function(){
$(window).one('mousemove', window.onafterprint);
}, 1);
</script>
window.print는 크롬에서 동기적으로 동작합니다.콘솔에서 사용해 보십시오.
window.print();
console.log("printed");
사용자가 인쇄 대화 상자를 닫지 않으면 "인쇄"가 표시되지 않습니다.
IE 또는 Firefox가 나중에 확인하고 업데이트할지 확신할 수 없습니다.
https://stackoverflow.com/a/15662720/687315 을 참조하십시오.해결 방법으로 다음을 들을 수 있습니다.afterPrint 및 합니다( 상자를 ).window.mediaMatchAPI는 미디어가 더 이상 "인쇄"(Firefox 및 Chrome)와 일치하지 않음을 나타냅니다.
사용자가 실제로 문서를 인쇄했거나 인쇄하지 않았을 수 있습니다.또한, 당신이 전화를 한다면,window.print()Chrome에서 너무 자주 사용하면 사용자가 인쇄하라는 메시지조차 표시되지 않았을 수 있습니다.
window.print()를 다른 함수에 넣기만 하면 언제 완료되는지 감지할 수 있습니다.
//function to call if you want to print
var onPrintFinished=function(printed){console.log("do something...");}
//print command
onPrintFinished(window.print());
Firefox, Google Chrome, IE에서 테스트됨
인쇄가 완료되었는지 확인하고 인쇄 창을 닫는 가장 간단한 방법:
window.onafterprint = function(){
window.onfocus = function(){
window.close();
}
};
이것은 실제로 크롬에서 저에게 효과가 있었습니다.저는 꽤 놀랐습니다.
jQuery(document).bind("keyup keydown", function(e){
if(e.ctrlKey && e.keyCode == 80){
Print(); e.preventDefault();
}
});
여기서 Print는 window.print()를 호출하는 함수입니다. Print()를 비활성화하면 순수 차단기로도 작동합니다.
사용자 3017502가 여기에 명시한 바와 같이
window.print()가 일시 중지되어 onPrintFinish 또는 onPrintBegin을 추가할 수 있습니다.
function Print(){
onPrintBegin
window.print();
onPrintFinish();
}
IE, FF, Chrome을 테스트했으며 모두 작동합니다.
setTimeout(function () { window.print(); }, 500);
window.onfocus = function () { setTimeout(function () { window.close(); }, 500); }
인쇄 대화 상자가 사라질 때까지 기다리려면 창에서 포커스 바인딩을 사용합니다.
print();
var handler = function(){
//unbind task();
$(window).unbind("focus",handler);
}
$(window).bind("focus",handler);
핸들러 함수에 언바인드를 삽입하여 포커스 이벤트가 윈도우에 본드를 유지하는 것을 방지합니다.
w = window.open(url, '_blank')을 사용하여 새 창에서 인쇄한 후 w.lookup;w.close()를 시도하고 페이지가 닫혔을 때를 감지합니다.모든 브라우저에서 작동합니다.
w = window.open(url, '_blank');
w.onunload = function(){
console.log('closed!');
}
w.focus();
w.print();
w.close();
인쇄 완료 후 창이 닫힙니다.
$(창구)로 작동합니다.초점을 맞추다
var w;
var src = 'http://pagetoprint';
if (/chrom(e|ium)/.test(navigator.userAgent.toLowerCase())) {
w = $('<iframe></iframe>');
w.attr('src', src);
w.css('display', 'none');
$('body').append(w);
w.load(function() {
w[0].focus();
w[0].contentWindow.print();
});
$(window).focus(function() {
console.log('After print');
});
}
else {
w = window.open(src);
$(w).unload(function() {
console.log('After print');
});
}
저는 윈도우 포커스 접근법이 옳다고 생각합니다.숨겨진 iframe에서 PDF url blob을 열고 인쇄하고자 했던 예가 있습니다.인쇄 또는 취소 후 iframe을 제거하고 싶었습니다.
/**
* printBlob will create if not exists an iframe to load
* the pdf. Once the window is loaded, the PDF is printed.
* It then creates a one-time event to remove the iframe from
* the window.
* @param {string} src Blob or any printable url.
*/
export const printBlob = (src) => {
if (typeof window === 'undefined') {
throw new Error('You cannot print url without defined window.');
}
const iframeId = 'pdf-print-iframe';
let iframe = document.getElementById(iframeId);
if (!iframe) {
iframe = document.createElement('iframe');
iframe.setAttribute('id', iframeId);
iframe.setAttribute('style', 'position:absolute;left:-9999px');
document.body.append(iframe);
}
iframe.setAttribute('src', src);
iframe.addEventListener('load', () => {
iframe.contentWindow.focus();
iframe.contentWindow.print();
const infanticide = () => {
iframe.parentElement.removeChild(iframe);
window.removeEventListener('focus', infanticide);
}
window.addEventListener('focus', infanticide);
});
};
인쇄 후 브라우저 동작이 다르기 때문에 어렵습니다.은 내부적으로 대화를 데크스톱크내롬처대인때기리인않다바습니가뀌지포후스커쇄문에화하쇄를부은로적으▁desktop▁after다않▁intern▁chrome데습니▁handles▁however스▁dialogue,▁focus바지뀌▁the.afterprint이벤트는 여기서 잘 작동합니다(현재 81.0 기준).반면에, 모바일 장치의 Chrome과 대부분의 다른 브라우저들은 인쇄 후 초점을 이동합니다.afterprint이벤트가 여기서 일관되게 작동하지 않습니다.모바일 기기에서 마우스 이동 이벤트가 작동하지 않습니다.
데스크톱 크롬인지 탐지하고, 예인 경우 애프터프린트 이벤트를 사용합니다.아니오인 경우 포커스 기반 탐지를 사용합니다.마우스 이동 이벤트(데스크톱에서만 작동)를 함께 사용하여 더 많은 브라우저와 더 많은 시나리오를 다룰 수도 있습니다.
흠, 모두에게 상기시키기 위해, 애프터 프린트가 인쇄 동작 버튼을 결정하지 않고 인쇄 창이 닫히거나 닫힐 때마다 실행된다는 것을 상기시키기 위해, 프린트 창을 닫는 취소 버튼이나 esc 키 모두가 아직 실제 인쇄가 발생하지 않는 동안 애프터 프린트를 고려합니다.
저는 저와 같은 문제를 가진 사람들을 위해 해결책을 제시합니다.저는 Chrome 브라우저를 사용하고 있으며, 제 프로젝트에서는 PDF를 인쇄하기 위한 iframe을 만듭니다.하지만 Afterprint 이벤트를 바인딩하면 작동하지 않습니다.
다음 코드는 포커스 이벤트를 바인딩하여 인쇄가 완료되었는지 여부를 감지합니다.
const iframe = document.createElement('iframe');
iframe.style.display = 'none';
iframe.src = url;
iframe.onload = function () {
console.log('load iframe done')
const handle = () => {
window.removeEventListener('focus', handle)
// do something...
}
window.addEventListener('focus', handle)
iframe.focus()
iframe.contentWindow.print()
}
document.body.appendChild(iframe)
window.on before print 및 window.on after print를 구현하는 중
Chrome v 78.0.3904.70에서 window.print() 뒤의 window.close() 호출이 작동하지 않습니다.
이에 접근하기 위해 저는 아담의 대답을 간단한 수정과 함께 사용하고 있습니다.
function print() {
(function () {
let afterPrintCounter = !!window.chrome ? 0 : 1;
let beforePrintCounter = !!window.chrome ? 0 : 1;
var beforePrint = function () {
beforePrintCounter++;
if (beforePrintCounter === 2) {
console.log('Functionality to run before printing.');
}
};
var afterPrint = function () {
afterPrintCounter++;
if (afterPrintCounter === 2) {
console.log('Functionality to run after printing.');
//window.close();
}
};
if (window.matchMedia) {
var mediaQueryList = window.matchMedia('print');
mediaQueryList.addListener(function (mql) {
if (mql.matches) {
beforePrint();
} else {
afterPrint();
}
});
}
window.onbeforeprint = beforePrint;
window.onafterprint = afterPrint;
}());
//window.print(); //To print the page when it is loaded
}
여기서 부르겠습니다.
<body onload="print();">
이것은 나에게 효과가 있습니다.다른 브라우저에서 이 이벤트를 처리할 수 있도록 두 기능 모두에 대해 카운터를 사용합니다(Chrome에서는 두 번, Mozilla에서는 한 번).브라우저를 검색하려면 다음 답변을 참조할 수 있습니다.
언급URL : https://stackoverflow.com/questions/18325025/how-to-detect-window-print-finish
'source' 카테고리의 다른 글
| 여러 행을 하나의 행으로 결합하는 방법 (0) | 2023.08.29 |
|---|---|
| Quartz Core, Core Graphics 및 Quartz 2D의 차이점은 무엇입니까? (0) | 2023.08.29 |
| MYSQL 데이터베이스의 모든 외부 키 삭제 (0) | 2023.08.29 |
| SQL null 값이 결과에 표시되지 않습니다. (0) | 2023.08.29 |
| MySQL: FULL OUTER JOIN - 열 하나를 병합하려면 어떻게 해야 합니까? (0) | 2023.08.29 |