Skip to content

Instantly share code, notes, and snippets.

@stefansundin
Last active October 24, 2024 11:34
Show Gist options
  • Save stefansundin/65e3d6db697636d8e7f1 to your computer and use it in GitHub Desktop.
Save stefansundin/65e3d6db697636d8e7f1 to your computer and use it in GitHub Desktop.
Makes the YouTube shortcuts work even if the player is not focused. Install Greasemonkey/Tampermonkey first, then click [Raw] to install.
// ==UserScript==
// @name YouTube global shortcuts
// @namespace https://gist.github.com/stefansundin/
// @homepage https://gist.github.com/stefansundin/65e3d6db697636d8e7f1
// @downloadURL https://gist.github.com/stefansundin/65e3d6db697636d8e7f1/raw/youtube-global-shortcuts.user.js
// @version 1.1
// @author Stefan Sundin
// @description Makes the YouTube shortcuts work even if the player is not focused.
// @icon https://www.youtube.com/favicon.ico
// @match https://www.youtube.com/*
// ==/UserScript==
// Space = Pause/play
// F = Toggle fullscreen
// M = Toggle mute
// P = Previous video (if in playlist)
// N = Next video (if in playlist)
// left and right keys focuses the button, but the first keydown won't trigger seeking unfortunately
// P and N already works without this userscript, but you must hold shift.
// Use Ctrl+Space to scroll down, Shift+Space to scroll up
window.addEventListener('keydown', function(e) {
var button = document.getElementsByClassName('ytp-play-button')[0] || document.getElementById('movie_player');
if (!button) return;
console.log(e);
// Skip if in comment reply form, or search field
if (['TEXTAREA','INPUT'].indexOf(e.srcElement.tagName) !== -1 || ['yt-commentbox-text','yt-simplebox-text'].indexOf(e.srcElement.className) !== -1) return;
var c = String.fromCharCode(e.keyCode).toLowerCase();
if (c == ' ' || e.keyCode == 37 || e.keyCode == 39) { // 37 = left key, 39 = right key
if (c == ' ' && (e.shiftKey || e.ctrlKey)) return;
if (e.srcElement != button) {
button.focus();
if (c == ' ') button.click();
}
}
else if (c == 'n') {
document.getElementsByClassName('ytp-next-button')[0].click();
}
else if (c == 'p') {
document.getElementsByClassName('ytp-prev-button')[0].click();
}
});
@ozturkkl
Copy link

Man, you are a legend, thank you for making this. Can't believe Google is so bad at not implementing this.

@stefansundin
Copy link
Author

Disclaimer: I have not used this for years and I doubt it still works. I think YouTube does have some global shortcuts these days, like the space key.

USE AT YOUR OWN RISK!

@ozturkkl
Copy link

Yeah, thank you for the warning. What I wanted was a little simpler so I didn't use your code but learned from it. 🙏🙏

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment