Prevent printing with Ctrl+P

Q: How can I prevent the printing dialog from appearing when the Ctrl+P keyboard shortcut is used?

A: You can listen to the keydown event in the capture phase and, if the Ctrl+P shortcut combination (or ⌘+P in Mac) is detected, call both event.preventDefault() and event.stopImmediatePropagation() to prevent both PSPDFKit printing and the default printing dialog from appearing.

Making this work in IE11 involves some extra work, like blocking the main thread so as to prevent the default printing dialog from showing up:

Copy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
PSPDFKit.load(configuration).then(instance => {
  const isIE11 = navigator.userAgent.indexOf("Trident/") > -1;
  instance.contentDocument.addEventListener(
    "keydown",
    keyDownHandler,
    isIE11
      ? {
          capture: true
        }
      : true
  );
  document.addEventListener(
    "keydown",
    keyDownHandler,
    isIE11
      ? {
          capture: true
        }
      : true
  );

  function keyDownHandler(event) {
    // Watch for `metaKey` too (⌘ in Mac)
    if ((event.ctrlKey || event.metaKey) && event.keyCode === 80) {
      // Is the browser IE11?
      if (isIE11) {
        const end = Date.now() + 4000; // block the main thread for 4s.
        while (Date.now() < end) {
          // Deliberately no-op
        }
      }

      event.preventDefault();
      event.stopImmediatePropagation();
      console.log("Ctrl+P shortcut detected");
    }
  }
});

This has been tested with PSPDFKit for Web 2020.1.2.