Youtube Spacebar Fix

Force spacebar to play/pause videos

当前为 2024-02-15 提交的版本,查看 最新版本

// ==UserScript==
// @name         Youtube Spacebar Fix
// @namespace    YouTube Spacebar Fix
// @description  Force spacebar to play/pause videos
// @version      2.1
// @author       DryChicken
// @match        http://*.youtube.com/*
// @match        https://*.youtube.com/*
// @exclude      https://*.youtube.com/embed/*
// @grant        none
// @license      MIT
// ==/UserScript==

// Function to determine if on a YouTube Short
function isYouTubeShort() {
	const currentUrl = window.location.href;
	return currentUrl.includes('shorts')
}

// Function to simulate the pressing and releasing of a key
function simulateKeyPress(key) {
	simulateKeyDown(key);
	simulateKeyUp(key);
}

function simulateKeyDown(key) {
	let keydownEvent = new KeyboardEvent('keydown', {
		key: key,
		keyCode: key.toUpperCase().charCodeAt(0),
		which: key.toUpperCase().charCodeAt(0),
		bubbles: true,
	});
	document.dispatchEvent(keydownEvent);
	console.log(`keydown ${key}`);
}

function simulateKeyUp(key) {
	let keyupEvent = new KeyboardEvent('keyup', {
		key: key,
        keyCode: key.toUpperCase().charCodeAt(0),
        which: key.toUpperCase().charCodeAt(0),
        bubbles: true,
    });
	document.dispatchEvent(keyupEvent);
	console.log(`keyup ${key}`);
}

function shortsPlayPause() {
	const shortsPlayer = document.querySelector('#shorts-player');
	if (shortsPlayer) shortsPlayer.click();
}

// Keyup on spacebar - when it works, is YouTube's default play/pause video
document.addEventListener("keyup", function(event) {
	if (event.key !== " ") return;

	// If in search bar or comment input
	let ae = document.activeElement;
	if (ae.tagName.toLowerCase() == "input" || ae.hasAttribute("contenteditable")) return;
	
	if (isYouTubeShort()) return;

	event.preventDefault();
	event.stopImmediatePropagation();
}, true);

// Keydown on spacebar also causes unexpected play/pause events
// Use keydown on spacebar to trigger our simulated play/pause action
document.addEventListener('keydown', function(event) {
	if (event.key !== " ") return;

	// If in search bar or comment input
	let ae = document.activeElement;
	if (ae.tagName.toLowerCase() == "input" || ae.hasAttribute("contenteditable")) return;
	
	event.preventDefault();
	event.stopImmediatePropagation();

	if (isYouTubeShort()) {
		shortsPlayPause();
		return;
	}

	simulateKeyPress('k');

}, true);

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址