Search code examples
javascripthtmlkeypresskeydown

JavaScript `event.preventDefault()` is useless for `alt+tab` in Windows


I received a new requirement in a project that we have to prevent Windows' alt+tab hot keys to prevent switches between windows.

After a lot of effort, I can prevent alt,ctrl,tab,shift,ctrl+s,ctrl+c,ctrl+v, etc., but I'm not able to prevent alt+tab, whether it's Firefox or Chrome.

I searched in MDN and finally found this: prevent the default action of the corresponding key down event in Chrome

So my guess is that alt+tab is a Windows system hot key but not the browser's. And event.preventDefault() can only prevent the events corresponding to the browser.

Does anyone have a more detailed explanation?

The following is my code:

<!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>

Solution

  • event.preventDefault() can only prevent the events corresponding to the browser.

    More precisely, event.preventDefault() can only prevent the action of events that the browser receives and decides to pass on to the web page.

    Alt+Tab is handled outside the browser entirely, by the Windows DWM. Under most circumstances, this shortcut isn't passed to desktop applications at all. Since web browsers don't go out of their way to capture it, they will never "see" the event at all. The same principle applies for Ctrl+Alt+Del.

    Some browsers will also "protect" certain keyboard shortcuts by never passing them to the web page, so that users can rely on these shortcuts always behaving consistently. For example, Chrome will protect any keyboard event which maps to one of the following commands:

    • Close Tab (Ctrl+W)
    • Close Window (Ctrl+Shift+W)
    • New Incognito Window (Ctrl+Shift+N)
    • New Tab (Ctrl+T)
    • New Window (Ctrl+N)
    • Restore Tab (Ctrl+Shift+T)
    • Select Next Tab (Ctrl+Tab, Ctrl+PageDown)
    • Select Previous Tab (Ctrl+Shift+Tab, Ctrl+PageUp)
    • Exit (Alt+F4, Cmd+Q)