I'm trying to set a TamperMonkey
script to make a keyboard key pause the native Chrome video player without the need to click on it or use the Space Bar
To achieve this, I tried to set a script that would trigger the click action in an x, y coordinate
where the video is displayed on the page.
So far, it didn't work.
// 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);
})();
Can anyone enlighten me on how to make this video pause with the key Q
?
Native HTMLVideoElement
's don't play/pause when clicked on (at least in Google Chrome; in Safari on MacOS they do, but you shouldn't rely on specific browers), so you'll need to use the .play()
and .pause()
methods, determining whether to play or pause based off of that .paused
readonly boolean. It would be great if there was just a .togglePlayback()
method, but there isn't.
(BTW, using KeyboardEvent.keyCode
is depricated in favor of KeyboardEvent.key
. It still works in major web browsers for backwards compatibility, but it's been officially deprecated in the standards)
On StackOverflow, make sure that you click anywhere inside the code snippet (the white box) once you click the blue button.
(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>