1

I would like to detect keyboard events without having to click into the window first. Keyboard events should not have to rely on a mouse so this seems strange. I am using the latest version of Firefox.

I have tried first adding focus to the window, document and body in a few ways but so far no luck.

I would give a jsfiddle link but that runs inside an iframe which I think is a different situation and solution.

Here is what I have tried:

(No jQuery please!)

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title></title>
    <meta name="description" content="">
    <meta name="author" content="">
</head>
<body>

    <p>Hello world.</p>

    <script>

        document.addEventListener("DOMContentLoaded", function(e) {

            // none of these seem to help
            document.body.focus();

            //document.focus(); 

            //window.focus();

            //top.document.focus();

            //parent.document.focus();

            //document.documentElement.focus();

        });

        // not triggered until after clicking in the window
        document.addEventListener("keydown", function(e) {
            console.log("keydown", e);
        });

    </script>
</body>
</html>

Update

With the developer tools closed, the keyboard events trigger fine (without the need to set focus).

How can we take the focus back away from the console or developer tools window (even though it is unlikely that a regular user would have them open)?

  • 1
    What do you want to do exactly? – Lixus Oct 16 '17 at 17:44
  • detect keyboard events without having to click into the window first –  Oct 16 '17 at 17:45
  • I can reproduce the problem on Chrome v61.0.3163.100. – moffeltje Oct 16 '17 at 18:00
  • 1
    Just realized the problem only happens with the developer tools open (added update) –  Oct 16 '17 at 18:03
  • It actually only happens when the developer tools have the focus when refreshing the page. I would say that this behaviour is by design. – NineBerry Oct 16 '17 at 18:07
  • Similar issue: [Keyboard shortcut to switch focus from web developer tools to page in Chrome](https://stackoverflow.com/questions/10981973/keyboard-shortcut-to-switch-focus-from-web-developer-tools-to-page-in-chrome) – NineBerry Oct 16 '17 at 18:11
  • Similar issue: [Set focus on web page rather than Firefox debugger after refreshing page](https://stackoverflow.com/questions/16493107/set-focus-on-web-page-rather-than-firefox-debugger-after-refreshing-page) – NineBerry Oct 16 '17 at 18:12

1 Answers1

0

I think it happens when you open developer console. That way the page loses focus. To verify:

// not triggered until after clicking in the window
document.addEventListener("keydown", function(e) {
    alert("keydown", e);
});
moffeltje
  • 4,521
  • 4
  • 33
  • 57