Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if a user prints something via javascript

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/

like image 635
CodePuppe Avatar asked Sep 03 '26 06:09

CodePuppe


1 Answers

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.

like image 155
Evgeniy Volk Avatar answered Sep 04 '26 20:09

Evgeniy Volk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!