JavaScript `event.preventDefault()` 对 Windows 中的 `alt+tab` 没用
JavaScript `event.preventDefault()` is useless for `alt+tab` in Windows
我在一个项目中收到一个新需求,我们必须防止 Windows' alt+tab 热键到防止在 windows 之间切换。
经过一番努力,我可以阻止alt,ctrl,tab, shift,ctrl+s,ctrl+c,ctrl+v,等等,但是我无法阻止 alt+tab,不管是火狐还是Chrome.
我在 MDN 中搜索,终于找到了这个:prevent the default action of the corresponding key down event in Chrome
所以我的猜测是 alt+tab 是一个 Windows 系统热键而不是浏览器的。而event.preventDefault()
只能阻止浏览器对应的事件
谁有更详细的解释吗?
以下是我的代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
document.addEventListener("keydown", function(e) {
//tab keyCode===9
//I hope to prevent alt+tab event action in windows
if (e.altKey && e.keyCode === 9) {
e.preventDefault(); //why not come in?
}
}, false)
</script>
</body>
</html>
event.preventDefault()
can only prevent the events corresponding to the browser.
更准确地说,event.preventDefault()
只能阻止浏览器接收并决定传递给网页的事件的动作。
Alt+Tab 完全由 Windows DWM 在浏览器之外处理。在大多数情况下,此快捷方式根本不会传递到桌面应用程序。由于网络浏览器不会特意捕获它,因此它们根本不会 "see" 该事件。同样的原理适用于Ctrl+Alt+Del。
某些浏览器还会 "protect" 某些键盘快捷键,不会将它们传递给网页,因此用户可以依赖这些快捷键始终保持一致的行为。例如,Chrome 将保护映射到以下命令之一的任何键盘事件:
- 关闭选项卡 (Ctrl+W)
- 关闭Window (Ctrl+Shift+W)
- 新隐身模式Window (Ctrl+Shift+N)
- 新标签页 (Ctrl+T)
- 新建Window (Ctrl+N)
- 恢复选项卡 (Ctrl+Shift+T)
- Select 下一个选项卡(Ctrl+Tab、Ctrl+PageDown)
- Select 上一个选项卡(Ctrl+Shift+Tab、Ctrl+PageUp)
- 退出(Alt+F4,Cmd+Q)
我在一个项目中收到一个新需求,我们必须防止 Windows' alt+tab 热键到防止在 windows 之间切换。
经过一番努力,我可以阻止alt,ctrl,tab, shift,ctrl+s,ctrl+c,ctrl+v,等等,但是我无法阻止 alt+tab,不管是火狐还是Chrome.
我在 MDN 中搜索,终于找到了这个:prevent the default action of the corresponding key down event in Chrome
所以我的猜测是 alt+tab 是一个 Windows 系统热键而不是浏览器的。而event.preventDefault()
只能阻止浏览器对应的事件
谁有更详细的解释吗?
以下是我的代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
document.addEventListener("keydown", function(e) {
//tab keyCode===9
//I hope to prevent alt+tab event action in windows
if (e.altKey && e.keyCode === 9) {
e.preventDefault(); //why not come in?
}
}, false)
</script>
</body>
</html>
event.preventDefault()
can only prevent the events corresponding to the browser.
更准确地说,event.preventDefault()
只能阻止浏览器接收并决定传递给网页的事件的动作。
Alt+Tab 完全由 Windows DWM 在浏览器之外处理。在大多数情况下,此快捷方式根本不会传递到桌面应用程序。由于网络浏览器不会特意捕获它,因此它们根本不会 "see" 该事件。同样的原理适用于Ctrl+Alt+Del。
某些浏览器还会 "protect" 某些键盘快捷键,不会将它们传递给网页,因此用户可以依赖这些快捷键始终保持一致的行为。例如,Chrome 将保护映射到以下命令之一的任何键盘事件:
- 关闭选项卡 (Ctrl+W)
- 关闭Window (Ctrl+Shift+W)
- 新隐身模式Window (Ctrl+Shift+N)
- 新标签页 (Ctrl+T)
- 新建Window (Ctrl+N)
- 恢复选项卡 (Ctrl+Shift+T)
- Select 下一个选项卡(Ctrl+Tab、Ctrl+PageDown)
- Select 上一个选项卡(Ctrl+Shift+Tab、Ctrl+PageUp)
- 退出(Alt+F4,Cmd+Q)