// ========================================================================== // YouTube plugin // ========================================================================== import utils from './../utils'; import controls from './../controls'; import ui from './../ui'; const youtube = { setup() { // Add embed class for responsive utils.toggleClass(this.elements.wrapper, this.config.classNames.embed, true); // Set aspect ratio youtube.setAspectRatio.call(this); // Setup API if (utils.is.object(window.YT) && utils.is.function(window.YT.Player)) { youtube.ready.call(this); } else { // Load the API utils.loadScript(this.config.urls.youtube.api); // Setup callback for the API // YouTube has it's own system of course... window.onYouTubeReadyCallbacks = window.onYouTubeReadyCallbacks || []; // Add to queue window.onYouTubeReadyCallbacks.push(() => { youtube.ready.call(this); }); // Set callback to process queue window.onYouTubeIframeAPIReady = () => { window.onYouTubeReadyCallbacks.forEach(callback => { callback(); }); }; } }, // Get the media title getTitle(videoId) { // Try via undocumented API method first // This method disappears now and then though... // https://github.com/sampotts/plyr/issues/709 if (utils.is.function(this.embed.getVideoData)) { const { title } = this.embed.getVideoData(); if (utils.is.empty(title)) { this.config.title = title; ui.setTitle.call(this); return; } } // Or via Google API const key = this.config.keys.google; if (utils.is.string(key) && !utils.is.empty(key)) { const url = `https://www.googleapis.com/youtube/v3/videos?id=${videoId}&key=${key}&fields=items(snippet(title))&part=snippet`; utils .fetch(url) .then(result => { if (utils.is.object(result)) { this.config.title = result.items[0].snippet.title; ui.setTitle.call(this); } }) .catch(() => {}); } }, // Set aspect ratio setAspectRatio() { const ratio = this.config.ratio.split(':'); this.elements.wrapper.style.paddingBottom = `${100 / ratio[0] * ratio[1]}%`; }, // API ready ready() { const player = this; // Ignore already setup (race condition) const currentId = player.media.getAttribute('id'); if (!utils.is.empty(currentId) && currentId.startsWith('youtube-')) { return; } // Get the source URL or ID let source = player.media.getAttribute('src'); // Get from
if needed if (utils.is.empty(source)) { source = player.media.getAttribute(this.config.attributes.embed.id); } // Replace the