Files
Echoion/EchoionWeb/frontend/src/lib/youtube.ts
T
faumaray 24fecc90f3 making WEB
Signed-off-by: faumaray <faumaray@gmail.com>
2026-07-11 00:47:52 +03:00

76 lines
2.6 KiB
TypeScript

// Shared loader for the YouTube IFrame API. Both Watch Together and the Now
// Playing video preview use it; the script is injected once and callers await
// the same readiness promise.
//
// Console-error triage for the YouTube embeds (as seen in production behind
// the reverse proxy):
// - "Failed to execute 'postMessage' … target origin ('https://www.youtube.com')
// does not match the recipient window's origin" — the IFrame API guesses the
// embedder when no explicit origin is passed; fixed by youtubeEmbedVars().
// - "__Secure-YEC has been rejected … SameSite" — YouTube setting its own
// third-party cookie inside the iframe; the youtube-nocookie.com host
// reduces this noise but cannot eliminate it.
// - "Attempt to postMessage on disconnected port" — fires when an iframe is
// torn down mid-message (source switch, room leave); harmless.
// Privacy-enhanced embed host (see cookie note above). Pass as the
// (undeclared in @types/youtube) top-level `host` option of YT.Player.
export const YOUTUBE_EMBED_HOST = 'https://www.youtube-nocookie.com';
// playerVars every embed must pass: native controls stay hidden (the custom
// bar / sync logic owns playback), and enablejsapi + origin keep the API's
// postMessage channel bound to this page's real origin.
export function youtubeEmbedVars(
extra?: Record<string, string | number>
): YT.PlayerVars {
return {
rel: 0,
modestbranding: 1,
controls: 0,
disablekb: 1,
iv_load_policy: 3,
enablejsapi: 1,
origin: location.origin,
widget_referrer: location.origin,
...extra,
} as YT.PlayerVars;
}
let promise: Promise<void> | null = null;
export function loadYouTubeApi(): Promise<void> {
if (promise) return promise;
promise = new Promise((resolve) => {
const w = window as unknown as {
YT?: typeof YT;
onYouTubeIframeAPIReady?: () => void;
};
if (w.YT && w.YT.Player) {
resolve();
return;
}
const prev = w.onYouTubeIframeAPIReady;
w.onYouTubeIframeAPIReady = () => {
prev?.();
resolve();
};
if (!document.querySelector('script[data-yt-iframe-api]')) {
const tag = document.createElement('script');
tag.src = 'https://www.youtube.com/iframe_api';
tag.dataset.ytIframeApi = '1';
document.head.appendChild(tag);
}
});
return promise;
}
// Extract an 11-char YouTube video id from a watch/share/embed URL or a bare
// id, or null when the URL is not YouTube.
export function youtubeIdFromUrl(url: string | undefined | null): string | null {
if (!url) return null;
const m = url.match(/(?:v=|youtu\.be\/|\/embed\/)([\w-]{11})/);
if (m) return m[1];
if (/^[\w-]{11}$/.test(url)) return url;
return null;
}