YouTube Helper API.
Ten skrypt nie powinien być instalowany bezpośrednio. Jest to biblioteka dla innych skyptów do włączenia dyrektywą meta // @require https://update.greasyfork.org/scripts/549881/1841778/YouTube%20Helper%20API.js
This script functions as a library, intended to be imported into other userscripts rather than executed directly.
Please reference the Script Description on GreasyFork (right under the script title) for the exact @require URL.
Note: Copy the line from the description to ensure you are using the correct versioning format. The version will be URL-dependent and statically set. Updating to a newer library version requires modifying the
@requireURL.
Example format:
// @require https://update.greasyfork.org/scripts/549881/[VERSION_ID]/YouTube%20Helper%20API.js
The library utilizes a Hybrid Storage System that adapts to the available environment.
localStorage or sessionStorage is used if no @grant directives are provided, or if the Greasemonkey API is unavailable.GM.*) and Legacy (GM_*) standards.You may grant either set, or include both for maximum compatibility:
// Modern API (Asynchronous)
// @grant GM.getValue
// @grant GM.setValue
// @grant GM.deleteValue
// @grant GM.listValues
// Legacy API (Synchronous)
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_deleteValue
// @grant GM_listValues
apiProxyapiProxy over direct object accessWhile the library exposes raw player objects (e.g., youtubeHelperApi.player.api or .playerObject), relying on them directly to invoke YouTube functions is largely unsafe and not recommended.
The raw player object is volatile and may evaluate to null or lack bound methods depending on the page's current load state. Accessing it directly increases the risk of runtime exceptions (e.g., "undefined is not a function").
Use the apiProxy. It intercepts calls, dynamically verifies the player's readiness, and safely logs a warning instead of crashing if a requested method is missing.
// Safe - Checks readiness automatically
youtubeHelperApi.apiProxy.playVideo();
youtubeHelperApi.apiProxy.seekTo(10, true);
Avoid interacting with the .api property or the DOM element directly, as they bypass the library's internal safety checks.
// Unsafe - May crash if player.api is null or methods are uninitialized
youtubeHelperApi.player.api.playVideo();
youtubeHelperApi.player.playerObject.seekTo(10, true);
document.getElementById('movie_player').playVideo();
Data parsing is typically asynchronous. It is highly recommended to listen for the library's ready event before executing dependent logic, ensuring the API is fully populated.
api.EVENTSThe API provides an EVENTS dictionary to standardize event listener string values.
Standard Implementation:
const { eventTarget, EVENTS } = youtubeHelperApi;
eventTarget.addEventListener(EVENTS.API_READY, (event) => {
const { video, player, page } = event.detail;
console.log(`Loaded: ${video.title} (${video.id})`);
// Example: Restrict execution to "Watch" pages
if (page.type === 'watch') {
// Implementation logic...
}
});
EVENTS Constant |
Payload (event.detail) |
Description |
|---|---|---|
API_READY |
{ video, player, page, chat, ... } |
The main event. Fires when the API is ready and data is fully populated. |
API_UPDATE_STARTED |
null |
Fires immediately when navigation starts, before new data is processed. |
AD_DETECTED |
{ isPlayingAds: boolean } |
Fires when an ad sequence starts or concludes. |
VIDEO_LANGUAGE_UPDATED |
{ playingLanguage, originalLanguage, isAutoDubbed, isInit } |
Fires when audio tracks change (e.g., via auto-dubbing). |
CHAT_STATE_UPDATED |
{ isCollapsed } |
Fires when the live chat sidebar state changes. |
IFRAME_DETECTED |
null |
Fires early if the script determines it is executing within an embedded iframe. |
PLAYER_UPDATED |
null |
Fires natively when the underlying YouTube player triggers an update. |
🎥 Tracked Native Video Events
The API intercepts and re-dispatches native HTML5 video events through its eventTarget, providing clean hooks into video playback without manual DOM querying:
VIDEO_PLAY, VIDEO_PAUSE, VIDEO_SEEKING, VIDEO_SEEKED, VIDEO_ENDED, VIDEO_VOLUMECHANGE.
These objects are managed automatically and protected by a **Read-Only Proxy. Attempted write operations will be ignored and will log a warning to the console.
youtubeHelperApi.instanceMetadata describing the current library instance.
id (string): Unique UUID representing the current injection instance.shortId (string): A truncated substring of the instance ID.root (Window): The top-level global scope (unsafeWindow or window) for the instance.youtubeHelperApi.videoMetadata parameters regarding the active video.
id (string): The native YouTube Video ID.title (string): The video title string.channel (string): The author/channel name.channelId (string): The unique internal channel identifier.rawDescription (string): The text of the video description.lengthSeconds (number): Total video duration in seconds.viewCount (number): Total registered view count.likeCount (number): Total registered like count.rawUploadDate (string): Unparsed upload date string.rawPublishDate (string): Unparsed publish date string.uploadDate (Date|null): Parsed JavaScript Date object of the upload time.publishDate (Date|null): Parsed JavaScript Date object of the publish time.isCurrentlyLive (boolean): true if the video is currently broadcasting live.isLiveOrVodContent (boolean): true if the content is a livestream or an archived VOD.wasStreamedOrPremiered (boolean): true if the video was originally live or premiered.isFamilySafe (boolean): true if marked as family-safe content.thumbnails (Array): Collection of thumbnail metadata objects.playingLanguage (object|string): The active audio track object.originalLanguage (object): The native language track object (if defined).isAutoDubbed (boolean): true if the active track is flagged as an auto-dub.realCurrentProgress (number): Exact video playback time (compensates for ad duration).isTimeSpecified (boolean): true if a timestamp query parameter (e.g., &t=50s) is present.playlistId (string): The internal ID of the current playlist, if one is active.isInPlaylist (boolean): true if the client is currently navigating a playlist.youtubeHelperApi.playerContextual state of the player interface and related DOM nodes.
isPlayingAds (boolean): true if an ad is actively interrupting playback.isFullscreen (boolean): true if the client's browser is in fullscreen mode.isTheater (boolean): true if the player is set to theater mode.videoElement (HTMLVideoElement): Direct reference to the primary <video> DOM node.playerObject (HTMLElement): Direct reference to the main container (e.g., #movie_player).response (object): The raw ytInitialPlayerResponse JSON containing underlying metadata.api (object): The raw YouTube player API (It is recommended to use apiProxy instead).youtubeHelperApi.pageClient navigation parameters and layout state.
type (string): The current context: 'watch', 'shorts', 'playlist', 'search', 'home', or 'unknown'.isMobile (boolean): true if executing on the mobile domain (m.youtube.com).isIframe (boolean): true if executing inside an embedded iframe structure.manager (HTMLElement): The primary <ytd-page-manager> node.watchFlexy (HTMLElement): The primary <ytd-watch-flexy> node.youtubeHelperApi.chatState variables for the live chat environment.
isCollapsed (boolean): true if the chat interface is currently hidden.container (HTMLElement): The parent DOM container for the chat UI.iFrame (HTMLIFrameElement): The iframe node rendering the chat content.youtubeHelperApi.debug)An atomic logging interface that prevents performance overhead when disabled.
enabled (boolean): Master switch. Defaults to false.level (number): Verbosity threshold (0: Minimal, 1: Typical, 2: Detailed, 3: All, 4: Overkill).channels: System to isolate and filter specific log sources.
debug.channels.add('my_script') — Registers a new channel.debug.channels.subscribe('my_script') / .unsubscribe('my_script') — Toggles active output.const logger = debug.channels.get('my_script') — Retrieves the logger instance.logger.logTypical("Initializing sequence...") — Writes to the console if conditions are met.window.youtubeHelperRegistry)A globally bound debugging tool that tracks all active library instances across different scripts on the page.
instances (Map): Collection of all active APIs mapped by instance ID.list(): Outputs a formatted console table of active scripts, their ID, and current page context.toggleAllDebug() / setAllDebug(boolean): Globally alters the debug state of every injected instance.setAllDebugLevel(number): Globally synchronizes the logging threshold.youtubeHelperApi.playback)Utilities to safely query and modify playback and resolution states.
POSSIBLE_RESOLUTIONS: Dictionary mapping string labels ('hd1080', 'highres') to pixel integers.getOptimalResolution(label, usePremium): Returns the best matched internal format object for a requested target.setResolution(label, ignoreAvailable, usePremium): Safely dictates the internal player to shift quality states.reload(seconds): Hard reloads the active video element at the defined timestamp.reloadToCurrentProgress(): Reloads the stream at the exact current second (useful for buffering resets).youtubeHelperApi.storage)A robust storage abstraction layer providing optimistic concurrency to prevent race conditions.
api (object): Exposes underlying configuration (validTypes, validActions, and implementations).key (getter/setter): Designates a custom storage key to use instead of the auto-generated Instance ID.save(key, data, options): Asynchronously stores arbitrary data.load(key, defaultData): Retrieves data, returning the fallback defaultData if null.loadAndClean(key, defaultData): Retrieves data but purges any keys not present in defaultData (useful for migrations).update(key, mutatorCallback, defaultData, options): Safely mutates data utilizing retry loops to sidestep parallel script race conditions.delete(key, options): Hard deletes the data entry.list(): Returns an array containing all tracked storage keys.youtubeHelperApi.broadcast)Cross-tab or cross-instance communication using the native BroadcastChannel API.
EVENT_PREFIX (string): Prefix attached to fired events (defaults to 'broadcast:').subscribedChannels (Array): List of currently opened channel names.subscribe(channelName): Opens a channel and binds listeners to emit events to eventTarget.unsubscribe(channelName): Closes an active channel.notify(channelName, message): Dispatches a payload (including source ID and timestamp) to all listeners across tabs/instances.youtubeHelperApi.concurrency)Negotiation layer for determining locks over shared resources across isolated scripts.
acquireLock(lockName, leaseDurationMs, options): Attempts to register a lock. Returns an object dictating if the attempt was successful.releaseLock(lockName): Relinquishes ownership of the lock.maintainLock(lockName): Refreshes the expiration threshold for an actively held lock.youtubeHelperApi.gmCapabilities)Metadata indicating permissions granted by the environment:
isModern: true if asynchronous GM.* hooks are detected.isLegacy: true if synchronous GM_* hooks are detected.isMissing: true if no Greasemonkey standard APIs are exposed.features: Dictionary mapping exact permission features (storage, xmlhttpRequest, etc.) to booleans.This block can be provided to code-generation models. It adheres to the API architecture and establishes best practices regarding the EVENTS standard.
Note: The
@requireURL must be manually populated using the endpoint specified in the GreasyFork Script Description.
// ==UserScript==
// @name [Script Name]
// @namespace http://tampermonkey.net/
// @version 1.0
// @description Generated by AI using YouTube Helper API
// @author You
// @match https://www.youtube.com/*
// @require [INSERT LIBRARY URL FROM SCRIPT DESCRIPTION ABOVE]
// @grant none
// ==/UserScript==
(function() {
'use strict';
// 1. Safe API Binding
const api = youtubeHelperApi;
if (!api) return console.error('YouTube Helper API failed to load.');
// Destructure properties for readability
const { eventTarget, EVENTS, apiProxy, video, player, debug } = api;
// Optional: Engage debug logging
// debug.enabled = true;
// debug.level = 1;
// 2. Logic Execution
function runDemoLogic() {
// Guard: Prevent execution if an ad sequence is active
if (player.isPlayingAds) return;
console.group('📺 [Script Demo] Video Initialization');
// Parameter Observation (Read-Only)
console.log(`Title: "${video.title}"`);
console.log(`Channel: "${video.channel}"`);
console.log(`Duration: ${video.lengthSeconds} seconds`);
// Proxy Interaction (Calling Methods)
try {
// Note: apiProxy methods correspond to native player API functions
const currentVol = apiProxy.getVolume();
console.log(`Volume: ${currentVol}%`);
} catch (err) {
console.warn('Unable to evaluate volume via Proxy.');
}
console.groupEnd();
}
// 3. Environment Listeners (Entry Point)
// The framework fires 'API_READY' when native video data cycles successfully
eventTarget.addEventListener(EVENTS.API_READY, (event) => {
const { page } = event.detail;
if (page.type === 'watch') {
runDemoLogic();
} else {
console.log('Skipping execution for page type:', page.type);
}
});
// 4. Ad Handling (Cleanup/Pausing)
eventTarget.addEventListener(EVENTS.AD_DETECTED, (event) => {
if (event.detail.isPlayingAds) {
console.log('⛔ [Script Demo] Ad initialized. Halting execution.');
} else {
console.log('✅ [Script Demo] Ad terminated.');
}
});
})();