YouTube Helper API.
このスクリプトは単体で利用できません。右のようなメタデータを含むスクリプトから、ライブラリとして読み込まれます: // @require https://update.greatest.deepsurf.us/scripts/549881/1701682/YouTube%20Helper%20API.js
Quick Navigation:
This script is a library, meant to be imported into other userscripts rather than installed directly.
Instead of guessing the URL, please check the Script Description at the very top of this page (right under the script title). There, you will find a ready-to-copy line formatted specifically for inclusion.
Note: Please 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 new library version requires the
@require-d URL to be changed.
It will look exactly like this:
// @require [https://update.greatest.deepsurf.us/scripts/549881/](https://update.greatest.deepsurf.us/scripts/549881/)[VERSION_ID]/YouTube%20Helper%20API.js
The library features a Hybrid Storage System that adapts to your environment.
Native JS Mode: The library uses standard browser localStorage if no @grant directives are provided or if the Greasemonkey API is unavailable at runtime (fail-safe).
Warning: This storage is tied to the browser's site data. Clearing your browser cache or cookies will erase data saved this way.
Greasemonkey API Mode: To use the userscript manager's native storage (which persists through cache clears), you need to grant access to the API functions. The library automatically detects and supports both the Modern (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 (via youtubeHelperApi.player.api or .playerObject), relying on them directly to call YouTube functions is unsafe and not recommended.
The raw player object is volatile and can be null or missing methods depending on the page's load state. Accessing it directly puts your script at risk of crashing with "undefined is not a function" errors.
Use the apiProxy. It intercepts calls, verifies the player is actually ready, and logs a warning instead of crashing if a method is missing.
// Safe - Checks readiness automatically
youtubeHelperApi.apiProxy.playVideo();
youtubeHelperApi.apiProxy.seekTo(10, true);
Avoid accessing the .api property or the DOM element directly, as they bypass safety checks.
// Unsafe - May crash if player.api is null or methods aren't bound yet
youtubeHelperApi.player.api.playVideo();
youtubeHelperApi.player.playerObject.seekTo(10, true);
document.getElementById('movie_player').playVideo();
Data might not be available instantly. It is highly recommended to listen for the library's ready event to ensure the API is fully populated before running your logic.
yt-helper-api-readyFires whenever video data is populated (on initial load, navigation, or refresh).
Standard Implementation:
const { eventTarget } = youtubeHelperApi;
eventTarget.addEventListener('yt-helper-api-ready', (event) => {
const { video, player, page } = event.detail;
console.log(`Loaded: ${video.title} (${video.id})`);
// Example: Only run logic on "Watch" pages
if (page.type === 'watch') {
// Your code here
}
});
| Event Name | Payload (event.detail) |
Description |
|---|---|---|
yt-helper-api-ready |
{ video, player, page, chat } |
The main event. Fires when the API is ready and data is fully populated. |
yt-helper-api-update-started |
null |
Fires immediately when navigation starts, before new data is processed. |
yt-helper-api-ad-detected |
{ isPlayingAds: boolean } |
Fires when an ad starts or stops. |
yt-helper-api-playback-language-updated |
{ playingLanguage, originalLanguage, isAutoDubbed } |
Fires when audio tracks change (e.g. auto-dubbing). |
yt-helper-api-chat-state-updated |
{ isCollapsed, container, iFrame } |
Fires when the live chat sidebar is toggled. |
These objects are updated automatically. Please do not attempt to write to them manually.
youtubeHelperApi.videoMetadata regarding the currently loaded video.
id (string): The YouTube Video ID.title (string): The video title.channel (string): The channel name.channelId (string): The unique channel ID.rawDescription (string): The video description.lengthSeconds (number): Total duration in seconds.viewCount (number): Total view count.likeCount (number): Total like count.uploadDate (Date|null): JavaScript Date object of the upload time.publishDate (Date|null): JavaScript Date object of the publish time.isCurrentlyLive (boolean): true if the video is strictly a live stream occurring right now.isLiveOrVodContent (boolean): true if the content is a livestream or a VOD (archive) of a previous stream.wasStreamedOrPremiered (boolean): true if the video was originally broadcast live or premiered.isFamilySafe (boolean): true if the content is marked as family-safe.thumbnails (Array): Array of thumbnail objects containing URL, width, and height.playingLanguage (object|string): The currently active audio track object.originalLanguage (object): The original language track object (if available).isAutoDubbed (boolean): true if the current audio track is an AI-generated auto-dub.realCurrentProgress (number): Video playback time (ignores ad time).isTimeSpecified (boolean): true if the URL contains a timestamp (e.g., &t=50s).playlistId (string): The ID of the current playlist, if one is active.youtubeHelperApi.playerState of the player interface and DOM elements.
isPlayingAds (boolean): true if an ad is currently interrupting content.isFullscreen (boolean): true if the browser is currently in fullscreen mode.isTheater (boolean): true if the player is currently in theater mode.videoElement (HTMLVideoElement): Direct reference to the actual <video> DOM node.playerObject (HTMLElement): Reference to the main player container (e.g., #movie_player).response (object): The raw ytInitialPlayerResponse object containing deep metadata.api (object): The raw YouTube player API (Note: Use apiProxy instead of this for safety).youtubeHelperApi.pageContext awareness and navigation state.
type (string): 'watch', 'shorts', 'playlist', 'search', 'browse', or 'unknown'.isMobile (boolean): true if running on m.youtube.com.isIframe (boolean): true if running inside an embedded player.manager (HTMLElement): The <ytd-page-manager> element (Desktop only).watchFlexy (HTMLElement): The <ytd-watch-flexy> element (Desktop only).youtubeHelperApi.chatState of the live chat container (if applicable).
isCollapsed (boolean): true if the chat window is currently collapsed/hidden.container (HTMLElement): The main container element for the chat.iFrame (HTMLIFrameElement): The specific iframe element loading the chat interface.YouTube obscures quality selection; use these helpers to handle it reliably.
POSSIBLE_RESOLUTIONS: Dictionary mapping labels (e.g., 'hd1080', 'highres') to resolution integers.getOptimalResolution(label, usePremium): Finds the best matching internal format object for a requested label.setPlaybackResolution(label, ignoreAvailable, usePremium): Safely forces the player to switch qualities.Syncs data between Greasemonkey API storage (if granted) and localStorage.
saveToStorage(key, value): Saves JSON data.loadFromStorage(key, defaultValue): Loads data, returning default if null.loadAndCleanFromStorage(key, defaultValue): Loads data but strips any keys not present in the default structure (useful for schema updates).You can copy this code block when asking an AI to write a new script. It establishes the correct structure and includes a working example that logs video stats to the console.
Note: You must manually fill in the
@requireURL using the link found in the Script Description at the top of this page.
// ==UserScript==
// @name [Script Name]
// @namespace [http://tampermonkey.net/](http://tampermonkey.net/)
// @version 1.0
// @description Generated by AI using YouTube Helper API
// @author You
// @match [https://www.youtube.com/](https://www.youtube.com/)*
// @require [INSERT LIBRARY URL FROM SCRIPT DESCRIPTION ABOVE]
// @grant none
// ==/UserScript==
(function() {
'use strict';
// 1. Destructure API components for easy access
const { eventTarget, apiProxy, video, player } = youtubeHelperApi;
// 2. Define your main logic
function runDemoLogic() {
// Guard: double-check we aren't running during an ad
if (player.isPlayingAds) return;
console.group('📺 [Script Demo] Video Detected');
// Example A: Reading Metadata (Read-Only)
console.log(`Title: "${video.title}"`);
console.log(`Channel: ${video.channel}`);
console.log(`Duration: ${video.lengthSeconds} seconds`);
// Example B: Using the Safe API Proxy (Calling Functions)
// We use the proxy to safely ask for the volume without crashing
try {
const currentVol = apiProxy.getVolume();
console.log(`Volume: ${currentVol}%`);
} catch (err) {
console.warn('Could not read volume via Proxy');
}
console.groupEnd();
}
// 3. Listen for Page Load & Navigation (The Entry Point)
eventTarget.addEventListener('yt-helper-api-ready', (event) => {
const { page } = event.detail;
// Only run this logic on actual video "Watch" pages
if (page.type === 'watch') {
runDemoLogic();
}
});
// 4. Handle Ad Interruptions (Pause & Resume)
eventTarget.addEventListener('yt-helper-api-ad-detected', (event) => {
if (event.detail.isPlayingAds) {
console.log('⛔ [Script Demo] Ad started... pausing logic.');
} else {
console.log('✅ [Script Demo] Ad ended... resuming logic.');
runDemoLogic();
}
});
})();