YouTube Helper API.
当前为
此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.cn-greasyfork.org/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();
})();