Reputation: 119
I've got a problem with detecting a print event in javascript. For example, a user wats to print document and presses print in a web-page, then another window appers, e.g. to print from Adobe Reader, then appears another window of Adobe Reader where you can set properties, choose pages to print and what not...and there is the print button in this window. Can I actually detect when the user presses this print button inside this Adobe Reader window in browser using javascript?
I've already tried using onafterprint
but maybe I didn't do this correctly or I'dont know.
it was something like this inside my main js
file.
window.onbeforeprint = function() {
console.log('This will be called before the user prints.');
};
window.onafterprint = function() {
console.log('This will be called after the user prints');
};
I took that from here: https://www.tjvantoll.com/2012/06/15/detecting-print-requests-with-javascript/
Upvotes: 3
Views: 11443
Reputation: 11035
Have you tried using the matchMedia
in that same link?
(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;
}());
Haven't done the full battery of browser compatibility checks, but that code works and prints both statements for me in Safari 10.1.1 whereas the onafterprint stuff doesn't work (though I exported as pdf once I was in the print dialog, since I don't have a printer).
I'm assume by Adobe Reader you just mean the normal print popup where you select a printer and number of copies/which pages/etc, since as far as I'm aware Adobe Reader is a desktop software
Upvotes: -1
Reputation: 656
Do you realize that you code do nothing ? This one will help you.
(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;
}());
run it in your dev console on any open page, then hit ctrl-P and you should see message.
Upvotes: 3