使用 TamperMonkey 脚本在原生 Chrome HTML5 播放器上暂停视频

Pause video on native Chrome HTML5 Player with TamperMonkey Script

我正在尝试设置一个 TamperMonkey 脚本来使键盘按键暂停本机 Chrome 视频播放器,而无需单击它或使用 Space Bar

为了实现这一点,我尝试设置一个脚本,该脚本会在页面上显示视频的 x, y coordinate 中触发点击操作。

到目前为止,它没有奏效。

// PAUSE VIDEO - ASSIGNED TO *Q* KEY
    (function(){
    document.addEventListener('keydown', function(e) {
    if (e.keyCode == 81 && !e.shiftKey && !e.ctrlKey && !e.altKey && !e.metaKey) {
    document.elementFromPoint(448, 540).click(); // this should trigger the click on video to pause event
    }
    }, false);
    })();

谁能告诉我如何用 Q 键让这个视频暂停?

原生HTMLVideoElement点击时不会play/pause,所以需要使用.play().pause()方法,判断是否播放或基于 .paused 只读布尔值暂停。如果只有 .togglePlayback() 方法就好了,但是没有。

(顺便说一句,using KeyboardEvent.keyCode is depricated in favor of KeyboardEvent.key。为了向后兼容,它仍然适用于主要的网络浏览器,但在标准中已被正式弃用)

在 Whosebug 上,确保在单击蓝色按钮后单击代码片段(白框)内的任意位置。

(function () {
    document.addEventListener('keydown', function (e) {
            if (e.key == 'q' && !e.shiftKey && !e.ctrlKey && !e.altKey && !e.metaKey) {
                const video = document.querySelector('video');
                // or = document.elementFromPoint(448, 540); if that's where it will always be
                if (video.paused) video.play();
                else video.pause();
            }
        },
    );
})();
<!-- Simple video example -->
<!-- 'Big Buck Bunny' licensed under CC 3.0 by the Blender foundation. Hosted by archive.org -->
<!-- Poster from peach.blender.org -->
<video controls
    src="https://archive.org/download/BigBuckBunny_124/Content/big_buck_bunny_720p_surround.mp4"
    poster="https://peach.blender.org/wp-content/uploads/title_anouncement.jpg?x11217"
    width="300">
</video>