Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting browser print event happens two different ways in Chrome

I am currently using the most up-to-date version of Chrome (43.0.2357.130), and am experiencing a difference in printing functionality when calling print from window.print() vs using ⌘P.

When printing using window.print() it outputs to the console correctly. It outputs Before Print when the print dialog is opened, and After Print when the dialog is closed.

However, when using the Chrome menu, or ⌘P to print, it logs both Before Print, and After Print to the console when the print dialog opens.

Here is the code I am using, which works well in other browsers.

function beforePrint() {
    console.log('Before Print');
}

function afterPrint() {
    console.log('After Print');
}

if (window.matchMedia) {
    var mediaQueryList = window.matchMedia('print');
    mediaQueryList.addListener(function (mql) {
        (mql.matches) ? beforePrint() : afterPrint();
    });
}
else {
    // basically a fallback for < IE11
    window.addEventListener('beforeprint', beforePrint, false);
    window.addEventListener('afterprint', afterPrint, false);
}

Once again for clarity as if this was the console:

This is the output I expect:

> window.print()
  Before Print
  // Print Dialog is now open, I press cancel to close dialog
  After Print

This is the output I get when I use ⌘P or the menu to start print:

  Before Print
  After Print
  // Print Dialog is now open, but it is occurring in the wrong place

Is this a bug in Chrome, or is there another way to capture the event correctly?

Just for reference, here is the Can I Use support table for matchMedia

like image 581
KevBot Avatar asked Jun 23 '15 16:06

KevBot


1 Answers

It looks like it is probably just a bug with Chrome. https://bugs.chromium.org/p/chromium/issues/detail?id=422883

like image 177
Walt Avatar answered Nov 15 '22 00:11

Walt