Remap the Control + S button in javascript (or jquery)

Viewed 55

I've been having troubles with the Control + S button, I would like to remap the Control + S button to something else instead of the save page as window.

** I know that its not possible to disable it** I want the functionality like what https://www.hastebin.com/ has, where if you control + s it does an action. I've already tried

    $(window).keypress((e) => {
    if (!(e.which == 115 && e.ctrlKey) && !(e.which == 19)) return true;
    console.log('bruh');
    e.preventDefault();
    return false;
});

That DOES work, but the save as page still shows up, where as on hastebin, it does not when you do ctrl + S

Any ideas?

2 Answers

Use keydown rather than keypress:

$(window).on("keydown", (e) => {
    if (e.key === "s" && e.ctrlKey) {
        console.log("Ctrl+S");
        e.preventDefault();
    }
});
<div>Click here, then press Ctrl+S</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

In that example I've used the key property rather than the deprecated which property, but if you need to support obsolete browsers you could use which (perhaps as a fallback).

CTRL+S fires keydown event, not keypress event AFAIK.

$(window).on("keydown", (e) => {
    if (e.key === "s" && e.ctrlKey) e.preventDefault();
});
Related