Fadexz / Start YouTube Autoplay Off

// ==UserScript==
// @name            Start YouTube Autoplay Off
// @namespace       FadexzStartYouTubeAutoPlayOff
// @description     Turn off YouTube Autoplay button when loading the page. Useful for incognito mode or to ensure it always starts turned off. Note: Currently doesn't load when being redirected from Shorts.
// @author          Fadexz
// @copyright       2022, Fadexz (https://openuserjs.org/users/Fadexz)
// @license         MIT
// @version         1.1.3
// @match           *://www.youtube.com/watch?*v=*
// @run-at          document-end
// @grant           none
// ==/UserScript==


// Note: This should be increased if it ever doesn't toggle off the 'auto-play' button, however this will cause it to keep clicking
// for longer (will close opened menus) which will mainly affect unlisted and private video that have the button hidden from view
const Attempts_To_Turn_Off = 10;


(function() {

    'use strict';

    let autoplayToggle = document.getElementsByClassName('ytp-autonav-toggle-button')[0];
    let attempts = 1;

    let checkInterval = setInterval(function() {

        function turnAutoplayOff() {
            if (autoplayToggle.getAttribute('aria-checked') === "true" && attempts < Attempts_To_Turn_Off) {
                autoplayToggle.click();
            }
            else {
                clearInterval(checkInterval);
                //console.log("[Start YouTube Autoplay Off] Ended at", attempts, "attempts");
            }
        }

        turnAutoplayOff();

        attempts ++;

    }, 200);

})();