I am using printing in my project (Using HTML and javascript). In mozilla onbeforeprint and onafterprint is working properly but not working in chrome.
What works for Chrome is to check for 'matchmedia' in 'window' as in:
if ('matchMedia' in window) {
window.matchMedia('print').addListener(function (media) {
//do before-printing stuff
});
} else {
window.onbeforeprint = function () {
//do before-printing stuff
}
}
This works as of Chrome 63, according to their changelog.
Quick update, because support of printing events has improved a lot
Chrome doesn't support those events. Instead it supports 'window.matchMedia'. Also there is a bug in Chrome that prevents it to print all the pages. For this reason, I suggest you add a print button to your web page and ask users to use the button instead of printing via the Chrome menu.
var beforePrint = function() {
console.log("before");
};
var afterPrint = function() {
console.log("after");
};
var launchedFromMenu = true;
if (window.matchMedia) {
var mediaQueryList = window.matchMedia('print');
mediaQueryList.addListener(function(mql) {
if (mql.matches) {
if(launchedFromMenu) {
// https://bugs.chromium.org/p/chromium/issues/detail?id=571070
alert("There is a bug in Chrome/Opera and printing via the main menu does not work properly. Please use the 'print' icon on the page.");
}
beforePrint();
} else {
afterPrint();
}
});
}
// These are for Firefox
window.onbeforeprint = beforePrint;
window.onafterprint = afterPrint;
function printPage() {
window["beforePrint"]();
launchedFromMenu = false;
window.print();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With