Youtube Pause at the End

Pause Youtube video at the end.

Versione datata 15/02/2024. Vedi la nuova versione l'ultima versione.

// ==UserScript==
// @name         Youtube Pause at the End
// @namespace    http://tampermonkey.net/
// @version      2024-02-15
// @description  Pause Youtube video at the end.
// @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';
    /**
     * Get element with selector and call callback with it.
     * @param {string} selector Selector for the element.
     * @param {function} callback Callback function to call with the element.
     */
    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) {
            // Add event listener to video element
            video.addEventListener(
                // when video time updates
                'timeupdate',
                function () {
                    // If video is less or equal to one seconds from the end
                    if ((video.duration - video.currentTime) <= 2) {
                        // pause video.
                        video.pause()
                    }
                }
            )
        }
    )
})();