Last active
May 26, 2024 08:39
-
-
Save HPZ07/a21cefbe93086588d90810a5e1f0ac07 to your computer and use it in GitHub Desktop.
Fix YouTube's Alt-Tab Pause/Play Issue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ==UserScript== | |
// @name Fix YouTube's Alt-Tab Pause/Play Issue | |
// @namespace http://tampermonkey.net/ | |
// @version 0.4 | |
// @description Fix YouTube's Alt-Tab Pause/Play Issue | |
// @author HPZ07 | |
// @match https://www.youtube.com/* | |
// @icon https://www.google.com/s2/favicons?sz=64&domain=youtube.com | |
// @grant none | |
// ==/UserScript== | |
(function() { | |
'use strict'; | |
window.addEventListener('keyup', keyHandler); | |
window.addEventListener('keydown', keyDownHandler); | |
const nonTriggerableElements = ['search', 'contenteditable-root', 'gsfi ytd-searchbox', 'ytd-searchbox', 'style-scope yt-formatted-string']; | |
let video = document.querySelector('video'); | |
let videoState; | |
function canTriggerSpaceAction() { | |
return !nonTriggerableElements.some(element => { | |
return document.activeElement.matches(`.${element}`) || document.activeElement.id === element; | |
}); | |
} | |
function keyHandler(e) { | |
if (!canTriggerSpaceAction() || e.code !== 'Space' || !isWatchPage) return; | |
video = document.querySelector('video'); | |
if (videoState === "play") video.play();; | |
if (videoState === "pause") video.pause(); | |
} | |
function keyDownHandler(e) { | |
if(!isWatchPage) return; | |
videoState = video.paused ? "play" : "pause"; | |
keyHandler(e); | |
} | |
function isWatchPage() { | |
return /^\/watch/.test(location.pathname); | |
} | |
})(); |
If you open a video in a new tab and the first thing you do is Alt+Tab, it won't register the first space but will after that.
The space bar doesn't work correctly on embedded videos. You should exclude them with this line:
// @exclude https://www.youtube.com/embed/*
Awesome script! Thanks @HPZ07 !
Big Thanks
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
0.4 should fix the problem(hopefully). Using a wildcard character on YouTube (e.g., watch*) may not be ideal due to YouTube's asynchronous content loading.