Greasy Fork is available in English.

YouTube Helper API

YouTube Helper API.

Verzia zo dňa 17.09.2025. Pozri najnovšiu verziu.

Tento skript by nemal byť nainštalovaný priamo. Je to knižnica pre ďalšie skripty, ktorú by mali používať cez meta príkaz // @require https://update.greatest.deepsurf.us/scripts/549881/1662681/YouTube%20Helper%20API.js

// ==UserScript==
// @name            YouTube Helper API
// @author          ElectroKnight22
// @namespace       electroknight22_helper_api_namespace
// @version         0.0.1
// @license         MIT
// @description     YouTube Helper API.
// ==/UserScript==

/*jshint esversion: 11 */

(function () {
    'use strict';

    const IS_IFRAME = window.top !== window.self;
    const IS_MOBILE = window.location.hostname === 'm.youtube.com';
    const PLAYER_UPDATE_EVENT = IS_MOBILE ? 'state-navigateend' : 'yt-player-updated';

    const youtubePlayer = {
        container: null,
        api: null,
        video: null,
    };

    function fallbackGetPlayerApi() {
        if (window.location.pathname.startsWith('/shorts')) return document.querySelector('#shorts-player');
        if (window.location.pathname.startsWith('/watch')) return document.querySelector('#movie_player');
        return document.querySelector('.inline-preview-player');
    }

    function dispatchHelperApiReadyEvent() {
        const playerStateIncomplete = Object.values(youtubePlayer).some((value) => value === null);
        if (playerStateIncomplete) return;

        // Pass the youtube player to consumer scripts with a custom event.
        const event = new CustomEvent('yt-api-helper-api-ready', { detail: { ...youtubePlayer } });
        document.dispatchEvent(event);
    }

    function updatePlayerState(event) {
        const useFallback = !event?.target?.player_;
        youtubePlayer.container = event?.target;
        youtubePlayer.api = event?.target?.player_;
        if (useFallback) {
            youtubePlayer.api = fallbackGetPlayerApi();
            youtubePlayer.container = youtubePlayer.api.parentElement;
        }
        youtubePlayer.video = youtubePlayer.container.querySelector('video');
        dispatchHelperApiReadyEvent(); // Dispatch an event so consumer scripts can react.
    }

    function init() {
        if (IS_IFRAME) document.dispatchEvent(new Event('yt-helper-api-detected-iframe'));
        updatePlayerState();
        document.addEventListener(PLAYER_UPDATE_EVENT, updatePlayerState);
    }

    init();
})();