How to Detect Window.Print() Finish

How to detect window.print() finish

You can listen to the afterprint event.

https://developer.mozilla.org/en-US/docs/Web/API/window.onafterprint

window.onafterprint = function(){
console.log("Printing completed...");
}

It may be possible to use window.matchMedia to get this functionality in another way.

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

}());

Source: http://tjvantoll.com/2012/06/15/detecting-print-requests-with-javascript/

Confirmation message after window.print()

There are a few ways to make sure a print dialog is finished before running a code block. Browser support varies, so you may need to combine some of them to match your need. See below stackoverflow topics.

  • how to detect window.print() finish
  • Close window automatically after printing dialog closes

The following code should work for most modern browsers.

var printCompleteCallback = function () {
var conf = confirm('Confirm printing as successfull and mark Job Cards as Released?');
if (conf) {
if (a == true) {
$.post('PrintSuccess');
window.location = '/Menu';
}
}
}

window.print();
if (window.onafterprint) { //check if browser supports window.onafterprint event handler (Firefox and IE)
$(window).one("afterprint", printCompleteCallback);
}
else { //Use setTimeout solution if onafterprint is not supported (Chrome)
setTimeout(printCompleteCallback, 0);
}

Detecting browser print event

You can now detect a print request in IE 5+, Firefox 6+, Chrome 9+, and Safari 5+ using the following technique:

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

I go into more detail into what this is doing and what it can be used for at http://tjvantoll.com/2012/06/15/detecting-print-requests-with-javascript/.



Related Topics



Leave a reply



Submit