How does Google Sheets override browser shortcuts?

我与影子孤独终老i 提交于 2021-02-07 10:53:48

问题


I'm creating a complicated in-browser app and I'd like to use some keyboard shortcuts that are currently used by Chrome and/or the other major browsers. I searched online and couldn't find a way to override browser shortcuts, but I saw that Google Sheets has just the kind of functionality I want: a user can select an option to override browser shortcuts.

How does Google sheets make this work?

Update: To clarify, since this has gotten some downvotes: I'm aware of event.preventDefault(). The problem is that it does not seem to work for key combinations like Ctrl + t (open new tab).


回答1:


The general idea is to intercept the event and call event.preventDefault() on it if it corresponds to a shortcut that you want to override. For example, the following code will prevent you from navigating to your leftmost tab if you press control-1:

document.body.addEventListener('keydown', (event) => {
  // keyCode 49 corresponds to the "1" key
  if(event.keyCode==49 && event.ctrlKey) {
    event.preventDefault();
    console.log('default action prevented, doing custom action instead');
  }
});
body {
  background-color: yellow;
}
click me first

Repeat for as many keyCodes and modifiers as you want.



来源:https://stackoverflow.com/questions/52774572/how-does-google-sheets-override-browser-shortcuts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!