Safari YouTube Play/Pause Issue Solution

There was some change in the YouTube UI and it breaks some browsers including safari. Ton of posts on reddit and other forums. Not everyone seems to be affected.

PROBLEM: Pressing spacebar (play/pause) after switching tabs doesn’t play/pause the video and one has to click on the video to get it back into focus.

SOLUTION: Here is a UserScript that fixes that. Put it in “UserScripts” extension and that’s it. Also took inspiration from: GitHub - MrQuackDuck/CorrectPause: Firefox & Chrome extension that fixes YouTube issue with pressing Spacebar to (play/pause) videos..

// ==UserScript==
// @name        Enhanced YouTube Spacebar Control
// @namespace   https://www.youtube.com/
// @description Controls YouTube play/pause with spacebar while avoiding interference during typing.
// @match       https://www.youtube.com/*
// @grant       none
// ==/UserScript==

(function() {
    'use strict';

    let latestAction;

    // Elements on which pressing space won't play/pause the video
    let forbiddenElementsSelectors = [
        'input',
        'textarea',
        '#search',
        '[contenteditable="true"]', // General selector for editable content
        '.ytd-searchbox', // Specific to YouTube search boxes
        // Add other selectors as needed
    ];

    // Helper function to check if spacebar interactions are allowed
    function isSpaceAllowed() {
        return !document.activeElement.matches(forbiddenElementsSelectors.join(', '));
    }

    document.addEventListener('keydown', function(e) {
        if (!isSpaceAllowed() || e.code !== 'Space') return;

        let vid = document.querySelector('video');
        if (!vid) return;

        if (vid.paused || vid.ended) {
            play(vid);
        } else {
            pause(vid);
        }
        e.preventDefault(); // Prevent default scroll behavior
    });

    document.addEventListener('keyup', function(e) {
        if (!isSpaceAllowed() || e.code !== 'Space') return;

        let vid = document.querySelector('video');
        if (!vid) return;

        // Repeat the action to ensure consistency, based on the original extension logic
        if (latestAction === 'play') play(vid);
        else if (latestAction === 'pause') pause(vid);
    });

    function play(video) {
        latestAction = 'play';
        video.play();
    }

    function pause(video) {
        latestAction = 'pause';
        video.pause();
    }
})();

1 Like