Youtube: Spacebar to Play/Pause Videos

Force bind the spacebar to play/pause videos

您需要先安裝使用者腳本管理器擴展,如 TampermonkeyGreasemonkeyViolentmonkey 之後才能安裝該腳本。

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

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyUserscripts 後才能安裝該腳本。

你需要先安裝一款使用者腳本管理器擴展,比如 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);
	}
});