Youtube: Spacebar to Play/Pause Videos

Force bind the spacebar to play/pause videos

You will need to install an extension such as Tampermonkey, Greasemonkey or Violentmonkey to install this script.

You will need to install an extension such as Tampermonkey to install this script.

You will need to install an extension such as Tampermonkey or Violentmonkey to install this script.

You will need to install an extension such as Tampermonkey or Userscripts to install this script.

You will need to install an extension such as Tampermonkey to install this script.

You will need to install a user script manager extension to install this script.

(I already have a user script manager, let me install it!)

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

(I already have a user style manager, let me install it!)

// ==UserScript==
// @name         Youtube: Spacebar to Play/Pause Videos
// @namespace    ytSpacePauseKK
// @description  Force bind the spacebar to play/pause videos
// @version      1.7
// @author       Kai Krause <[email protected]>
// @match        http://*.youtube.com/*
// @match        https://*.youtube.com/*
// @exclude      https://*.youtube.com/embed/*
// @run-at       document-start
// @grant        none
// ==/UserScript==

let cachedMode = "";
document.addEventListener("keydown", function onEvent(e) {
	if (e.code !== "Space") return;

	let ae = document.activeElement;
	if (ae.tagName.toLowerCase() == "input" || ae.hasAttribute("contenteditable")) return;
	e.preventDefault();
	e.stopImmediatePropagation();

	if (document.location.hostname == "music.youtube.com") {
		document.querySelector("#play-pause-button").click();
	}
	else {
		let player = document.querySelector(".html5-video-player");
		if (player.classList.contains("paused-mode")) cachedMode = "paused-mode";
		if (player.classList.contains("playing-mode")) cachedMode = "playing-mode";
		if (player.classList.contains("ended-mode")) cachedMode = "ended-mode";

		setTimeout(() => {
			let player = document.querySelector(".html5-video-player");
			if (player.classList.contains(cachedMode)) {
				document.querySelector("button.ytp-play-button").click();
				cachedMode = "";
			}
		}, 200);
	}
});