How do I capture keyboard events while watching an

2019-02-28 07:19发布

问题:

I need to know when the user presses the escape key when watching an HTML5 video in fullscreen mode. Unfortunately any configured listeners on the document don't apply since when the user is watching an HTML5 video in fullscreen mode the system focus is on the native video player rather than the browser.

An alternative is listening for when focus reverts back from the native video player to the browser, but I'm unsure as to how I would capture this.

document.addEventListener('keydown', function (e) { console.log(e.keyCode); }, false);

The above successfully logs to the console when I press keys so long as I'm in the browser. As soon as an HTML5 video enters fullscreen mode, the browser obviously can no longer log key codes to the console.

What I'm trying to do is transition from one UI to another after exiting fullscreen mode.

EDIT

Potench's answer was useful as a starting point which is why I accepted it as that answer despite the following caveats:

  • It only works in Webkit browsers. :-)
  • As originally defined it does not work since video.webkitDisplayingFullscreen is true whenever the resize event fires.

I got this to work - only on Webkit browsers - by tapping into animation frames to constantly watch for the change in value:

var onFrame, isVideoFullscreen;

onFrame = window.requestAnimationFrame ||
          window.mozRequestAnimationFrame ||
          window.webkitRequestAnimationFrame ||
          window.oRequestAnimationFrame ||
          window.msRequestAnimationFrame ||
          function (fn) {
              setTimeout(fn, 1000 / 60);
          };

isVideoFullscreen = false;

function frame() {
    if (!isVideoFullscreen && video.webkitDisplayingFullscreen) {
        // entered fullscreen mode
        isVideoFullscreen = true;
    } else if (isVideoFullscreen && !video.webkitDisplayingFullscreen) {
        // exited fullscreen mode
        isVideoFullscreen = false;
    }
    onFrame(frame);
}
onFrame(frame);

回答1:

Ok I think I have a solution for you... I'm just going to assume you use jQuery for ease of writing this code.

I don't believe you'll be able to capture keyboard events while in Fullscreen mode... but you could do this to get notified when you enter or exit fullscreen mode.

var isVideoFullscreen = video.webkitDisplayingFullscreen;

$(window).bind("resize", function (e) {
    // check to see if your browser has exited fullscreen
    if (isVideoFullscreen != video.webkitDisplayingFullscreen) { // video fullscreen mode has changed
       isVideoFullscreen =  video.webkitDisplayingFullscreen;

       if (isVideoFullscreen) {
            // you have just ENTERED full screen video
       } else {
            // you have just EXITED full screen video
       }
    }
});

Hope this helps or points you in the right direction