I would like to use the key combination ctrl + shift + p to open a command palette similar to how one opens on https://vscode.dev. This appears to work fine in browsers on MacOS, however when I try to do the same on windows it will open a system print dialog.
I have tried to add an event listener for 'beforeprint' but I don't believe it is cancellable.
window.addEventListener('beforeprint', (event) => {
event.preventDefault();
event.stopPropagation();
});
I'm trying to prevent the print dialog in this handler for the keybind
document.addEventListener('keydown', (event) => {
if (event.key === 'p' && event.shiftKey && (event.ctrlKey || event.metaKey)) {
// Prevent browser print dialog
event.preventDefault();
// Prevent dev tools command palette from opening
event.stopPropagation();
// Do logic here
}
});
This handler works seems to work fine on MacOS safari and chrome but I cannot replicate the behavior on Windows where it opens the system print dialog.
I was able to resolve this issue by switching my check for event.key === 'p' to event.keyCode === 80. I did not have any need for the 'beforePrint' handler.
document.addEventListener('keydown', (event) => {
if (event.keyCode === 80 && event.shiftKey && (event.ctrlKey || event.metaKey)) {
// Prevent browser print dialog
event.preventDefault();
// Prevent dev tools command palette from opening
event.stopPropagation();
// Do logic here
}
});
If you are using/can use jQuery:
$(document).bind("keyup keydown", function(e) {
if (e.ctrlKey && e.keyCode == 80) {
alert("Do what ever you want here.")
return false; // Stops print
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
If you run it here, it won't work. Try running it on codepen or somewhere else.