Hugo Sum
Hugo Sum

Reputation: 243

How to disable browser default keybindings with Javascript?

I am building an editor with custom keybindings to control its behaviors. It worked well, but if I set a keybinding pattern that is already used by browser, my defined keybindings are ignored by the browser.

A list of browser keybindings: https://www.howtogeek.com/114518/47-keyboard-shortcuts-that-work-in-all-web-browsers/

My question is, how can I override these keybindings? Is it possible to do so with Javascript?

Upvotes: 0

Views: 1299

Answers (1)

Pavlos Karalis
Pavlos Karalis

Reputation: 2966

Either through an event listener or an "onkeydown" attribute, you can conditionally target combinations of key/keyCode, metaKey(command/windows), shiftKey, altKey, and ctrlKey:

window.addEventListener("keydown",(e)=>{
  const {key, keyCode, metaKey, shiftKey, altKey, ctrlKey} = e; 
  if(key === "c" && (ctrlKey || metaKey)){
    e.preventDefault();
    console.log("copy prevented");
  }
});
HIGHLIGHT AND TRY TO COPY THIS TEXT WITH CTRL + C or COMMAND + C

Upvotes: 1

Related Questions