YouTube Auto Reload When Video unavailable

Reloads YouTube when a video fails. Active tab only. May need to press F5 once on first visit.

// ==UserScript==
// @name         YouTube Auto Reload When Video unavailable 
// @name:zh-TW   YouTube 影片無法播放自動重整
// @name:ja      YouTubeの動画が再生できません時に自動リロード
// @namespace    https://example.com/
// @version      2.5
// @description  Reloads YouTube when a video fails. Active tab only. May need to press F5 once on first visit.
// @description:zh-TW 卡住的 YouTube 影片自動重新整理(僅限活頁籤)。首次可能需手動按一次 F5。
// @description:ja YouTubeの動画が読み込めない時に自動リロードします(アクティブタブのみ)。初回はF5が必要な場合があります。
// @match        https://www.youtube.com/watch*
// @grant        none
// @license      MIT
// ==/UserScript==

(function () {
    'use strict';

    let isReloading = false;

    const checkVideoStatus = () => {
        if (document.hidden) {
            return true; // 跳過背景頁檢查,避免誤 reload
        }

        const video = document.querySelector('video');
        const errorBox = document.querySelector('.ytp-error, .ytp-error-content-wrap');

        if (
            (errorBox && errorBox.offsetParent !== null) ||
            !video ||
            (video.currentTime === 0 && video.paused)
        ) {
            return false;
        }

        return true;
    };

    const tryReload = () => {
        if (isReloading) return;
        isReloading = true;
        location.reload();
    };

    const observer = new MutationObserver(() => {
        if (!checkVideoStatus()) {
            tryReload();
        }
    });

    const startObserver = () => {
        const target = document.body;
        if (!target) return;

        observer.observe(target, {
            childList: true,
            subtree: true
        });

        setTimeout(() => {
            if (!checkVideoStatus()) {
                tryReload();
            }
        }, 800);
    };

    window.addEventListener('load', startObserver);

    document.addEventListener('visibilitychange', () => {
        if (!document.hidden && !checkVideoStatus()) {
            tryReload();
        }
    });
})();

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址