Youtube: Spacebar to Play/Pause Videos

Force bind the spacebar to play/pause videos

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Greasemonkey 油猴子Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Userscripts ,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展后才能安装此脚本。

(我已经安装了用户脚本管理器,让我安装!)

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

(我已经安装了用户样式管理器,让我安装!)

// ==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);
	}
});