Reputation: 6742
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:
According to this SO and this MDN, the print event isn't cancelable, so how does google did it?
Upvotes: 0
Views: 1318
Reputation: 1796
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/
Upvotes: 1
Reputation: 19573
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();
}
})
Upvotes: 1