Detecting browser print event

Viewed 49957

Is it possible to detect when a user is printing something from their browser?

To complicate matters, if we are presenting a user with a PDF document in a new window is it possible to detect the printing of that document ( assuming the user prints it from the browser window)?

The closest I've been able to find is if we implement custom print functionality (something like this) and track when that is invoked

I'm primarily interested in a solution that works for internet explorer (6 or later)

4 Answers

For Internet Exploder, there are the events window.onbeforeprint and window.onafterprint but they don't work with any other browser and as a result they are usually useless.

They seem to work exactly the same for some reason, both executing their event handlers before the printing window opens.

But in case you want it anyway despite these caveats, here's an example:

window.onbeforeprint = function() {
    alert("Printing shall commence!");
}

For anyone reading this on 2020. The addListener function is mostly deprecated in favor of addEventListener except for Safari:

if (window.matchMedia) {
  const media = window.matchMedia("print");
  const myFunc = mediaQueryList => {
    if (mediaQueryList.matches) {
      doStuff();
    }
  };
  try {
    media.addEventListener("change", myFunc);
  } catch (error) {
    try {
    media.addListener(myFunc);
    } catch (error) {
      console.debug('Error', error)
    }
  }
}

Reference: This other S.O question

Related