0

I need to somehow prevent the user from printing in my Angular app and instead of displaying the default printing popup, display a custom layout like on google maps, if the user toggle the printing via the ctrl + p shortcut, the user is presented with a different layout and the print popup doesn't show up:

enter image description here

According to this SO and this MDN, the print event isn't cancelable, so how does google did it?

Runtime Terror
  • 6,242
  • 11
  • 50
  • 90
  • 1
    it just prevent the shurtcut. the "print" button will cause the popup – Sysix Nov 25 '20 at 19:02
  • One way you could make this happen is actually with CSS. You can define styles specifically for media types... like print. This way, you could hide everything and show your map – ControlAltDel Nov 25 '20 at 19:06

2 Answers2

1

As stated in the comment, you can hook into the keyboard shortcut event

document.body.addEventListener('keydown', function (event) {
    // listen for ctrl+p
    if (event.key === "p" && event.ctrlKey === true) {
        event.preventDefault();
        // do something...
        // ...
        // when you are ready to print
        window.print();
    }
})
chiliNUT
  • 18,989
  • 14
  • 66
  • 106
1

When sombody wants a "live" example, I created fast one here:

document.addEventListener('keydown', function (event) {
    // listen for ctrl+p
    if (event.key === "p" && event.ctrlKey === true) {
        event.preventDefault();
        
        // add class to html element
        document.documentElement.classList.toggle('print-layout');
    }
})

var printButton = document.querySelector('.print-button');

// just trigger print popup
printButton.addEventListener('click', function() {
    window.print();
})
body {
  background: red;
}


.print-button {
  display: none;
}

.print-layout body {
  background: white;
}

.print-layout .print-button {
  display: block;
}
<button class="print-button">Print Me</button>

Description:
Just prevent the STRG+P Shurtcut and add a CSS-Class.
This gives you the ability the customize your layout completly.

In your example (google maps) did include a "print" button.
In my example I tried to handle that too.

PS: JSFiddle Link when its not working here in stackoverflow: https://jsfiddle.net/drxf6gwz/

Sysix
  • 1,572
  • 1
  • 16
  • 23