Youtube pause on start

Pause Youtube video on start.

Verze ze dne 15. 02. 2024. Zobrazit nejnovější verzi.

// ==UserScript==
// @name         Youtube pause on start
// @namespace    http://tampermonkey.net/
// @version      2024-02-15
// @description  Pause Youtube video on start.
// @author       Santeri Hetekivi
// @match        https://www.youtube.com/watch?v=*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=youtube.com
// @grant        none
// ==/UserScript==

(function () {
    'use strict';
   function forElement(selector, callback) {
        // Init forElement.timeoutCount.
        if (forElement.timeoutCount === undefined) {
            forElement.timeoutCount = {}
        }
        // Init forElement.timeoutCount[selector].
        if (forElement.timeoutCount[selector] === undefined) {
            forElement.timeoutCount[selector] = 0
        }

        // Get element.
        const element = document.querySelector(selector)

        // If element not found.
        if (element === null) {
            // try again after timeout.
            setTimeout(
                function () {
                    forElement(selector, callback)
                },
                (
                    // Base timeout.
                    100
                    *
                    // Increase timeout after each try.
                    (forElement.timeoutCount[selector]++)
                )
            )
        }
        // If element found
        else {
            // reset timeout count
            forElement.timeoutCount[selector] = 0
            // and call callback with element.
            callback(element)
        }
    }

    // Run for
    forElement(
        // video element that has src attribute
        "video[src]",
        function (video) {
            // Init paused video ID.
            let pausedVideoId = null

            // Add event listener to video element
            video.addEventListener(
                // for playing event
                "playing",
                function () {
                    // Get current video ID from URL.
                    const videoId = (new URLSearchParams(window.location.search)).get("v")

                    // If video id is different than last paused video
                    if (pausedVideoId !== videoId) {
                        // pause video
                        video.pause()
                        // and update paused video ID.
                        pausedVideoId = videoId
                    }
                }
            )
        }
    )
})();