简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM