Skip to content

Instantly share code, notes, and snippets.

@HPZ07
Last active May 26, 2024 08:39
Show Gist options
  • Save HPZ07/a21cefbe93086588d90810a5e1f0ac07 to your computer and use it in GitHub Desktop.
Save HPZ07/a21cefbe93086588d90810a5e1f0ac07 to your computer and use it in GitHub Desktop.
Fix YouTube's Alt-Tab Pause/Play Issue
// ==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);
}
})();
@Orlean54
Copy link

Big Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment