1

I'm trying to prevent to have to hide/show a bunch of elements with CSS and instead render them only when printing, to do so I'm using this pattern:

const beforePrint = () => { console.log('beforePrint') };
const afterPrint = () => { console.log('afterPrint') };

if (window.matchMedia) {
  const mediaQueryList = window.matchMedia('print');
  mediaQueryList.addListener((mql) => {
    if (mql.matches) {
      beforePrint();
    } else {
      afterPrint();
    }
  });
}

window.addEventListener('beforeprint', this.handleBeforePrint);
window.addEventListener('afterprint', this.handleAfterPrint);

The console.log are triggered as expected but when I'm rendering elements instead of doing a console.log, it works only when the user does Ctrl+p and not when window.print is triggered.

Here is my example https://pw74zpl44x.codesandbox.io/ and the code (in React but it doesn't matter) https://codesandbox.io/s/pw74zpl44x

Calvein
  • 2,111
  • 13
  • 28
  • Possible duplicate of [Detecting browser print event happens two different ways in Chrome](https://stackoverflow.com/questions/31008434/detecting-browser-print-event-happens-two-different-ways-in-chrome) – KevBot Feb 05 '18 at 16:57
  • I have the issue on Firefox too – Calvein Feb 05 '18 at 16:59

0 Answers0