我正在尝试设置一个 TamperMonkey
脚本,让键盘按键暂停 native Chrome 视频播放器,而无需单击它或使用空格键
为了实现这一目标,我尝试设置一个脚本,该脚本将在页面上显示视频的 x, y 坐标
中触发点击操作。
到目前为止,还没有成功。
// 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
点击时不会播放/暂停(至少在 Google Chrome 中;在 MacOS 上的 Safari 中,但您不应该依赖特定的浏览器),因此您需要使用 .play( )
和 .pause()
方法,根据该 .paused
只读 bool 值确定是播放还是暂停。如果只有 .togglePlayback()
方法就太好了,但没有。
(顺便说一句, using KeyboardEvent.keyCode
is depricated 赞成 KeyboardEvent.key
。它仍然可以在主要的 Web 浏览器中工作以实现向后兼容性,但它已在标准中被正式弃用)
在 StackOverflow 上,单击蓝色按钮后,请确保单击代码片段(白色框)内的任意位置。
(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>
关于javascript - 使用 TamperMonkey 脚本在 native Chrome HTML5 播放器上暂停视频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68043883/