Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onbeforeprint and onafterprint is not working in Chrome and IE?

I am using printing in my project (Using HTML and javascript). In mozilla onbeforeprint and onafterprint is working properly but not working in chrome.

like image 607
Shanky_Richer Avatar asked Nov 28 '12 06:11

Shanky_Richer


4 Answers

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
                    }
                }
like image 82
samiup Avatar answered Oct 19 '22 03:10

samiup


This works as of Chrome 63, according to their changelog.

like image 33
Charley B. Avatar answered Oct 19 '22 02:10

Charley B.


Quick update, because support of printing events has improved a lot

  • Chrome 63, releases in December 2017, supports it source
  • Opera 50 as well
  • Edge supports it since the beginning
  • even old version 6 of IE (6!!) supports it
like image 2
Feugy Avatar answered Oct 19 '22 02:10

Feugy


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

}
like image 1
Caner Avatar answered Oct 19 '22 03:10

Caner