You can run your own special JavaScript by overriding the window.print
function. However, this is a different flow than someone clicking print from the navigation bar.
window.print
is the print flow as launched by the application.
var oldPrintFunction = window.print;
window.print = function () {
console.log('Gonna do some special stuff');
oldPrintFunction();
};
Working with user driven print events and programmed print events:
I had to go look this up as I had something I wrote a long time ago that did something similar, and it seems that I found it. This code watches for the media change to go to print
.
function beforePrint() {
console.log('Do something special before print');
}
function afterPrint() {
console.log('Do something after print');
}
if (window.matchMedia) {
window.matchMedia('print').addListener(function (mql) {
if (mql.matches) {
beforePrint();
}
else {
afterPrint();
}
});
}
// For IE, does not attach in browsers that do not support these events
window.addEventListener('beforeprint', beforePrint, false);
window.addEventListener('afterprint', afterPrint, false);
This will run whatever is in the beforePrint
function for calling window.print()
, or the user chooses to print using a browser flow (command+p, file->print), etc.
Please note: The afterprint
has a bug in Chrome, see my StackOverflow question here