Using fetch instead of xhr, grabbing title for YouTube

This commit is contained in:
Sam Potts 2017-11-16 11:38:06 +01:00
parent c64b8f6940
commit d7a1c44281
12 changed files with 47 additions and 50 deletions

2
demo/dist/demo.js vendored
View File

@ -1,3 +1,3 @@
document.addEventListener("DOMContentLoaded",function(){function e(e,t,o){e&&e.classList[o?"add":"remove"](t)}function t(t,a){if(t in n&&(a||t!==r)&&(r.length||t!==n.video)){switch(t){case n.video:o.source={type:"video",title:"View From A Blue Moon",sources:[{src:"https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.mp4",type:"video/mp4"}],poster:"https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.jpg",tracks:[{kind:"captions",label:"English",srclang:"en",src:"https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.en.vtt",default:!0},{kind:"captions",label:"French",srclang:"fr",src:"https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.fr.vtt"}]};break;case n.audio:o.source={type:"audio",title:"Kishi Bashi – “It All Began With A Burst”",sources:[{src:"https://cdn.plyr.io/static/demo/Kishi_Bashi_-_It_All_Began_With_a_Burst.mp3",type:"audio/mp3"},{src:"https://cdn.plyr.io/static/demo/Kishi_Bashi_-_It_All_Began_With_a_Burst.ogg",type:"audio/ogg"}]};break;case n.youtube:o.source={type:"video",title:"View From A Blue Moon",sources:[{src:"https://www.youtube.com/watch?v=bTqVqk7FSmY",type:"youtube"}]};break;case n.vimeo:o.source={type:"video",title:"View From A Blue Moon",sources:[{src:"https://vimeo.com/76979871",type:"vimeo"}]}}r=t,Array.from(i).forEach(function(t){return e(t.parentElement,"active",!1)}),e(document.querySelector('[data-source="'+t+'"]'),"active",!0),Array.from(document.querySelectorAll(".plyr__cite")).forEach(function(e){e.setAttribute("hidden","")}),document.querySelector(".plyr__cite--"+t).removeAttribute("hidden")}}window.shr&&window.shr.setup({count:{classname:"button__count"}});document.addEventListener("focusout",function(e){e.target.classList.remove("tab-focus")}),document.addEventListener("keydown",function(e){9===e.keyCode&&window.setTimeout(function(){document.activeElement.classList.add("tab-focus")},0)});var o=new window.Plyr("#player",{debug:!0,title:"View From A Blue Moon",iconUrl:"../dist/plyr.svg",keyboard:{global:!0},tooltips:{controls:!0},captions:{active:!0},controls:["play-large","play","progress","current-time","mute","volume","captions","settings","fullscreen","pip","airplay"]});window.player=o;var i=document.querySelectorAll("[data-source]"),n={video:"video",audio:"audio",youtube:"youtube",vimeo:"vimeo"},r=window.location.hash.replace("#",""),a=window.history&&window.history.pushState;if(Array.from(i).forEach(function(e){e.addEventListener("click",function(){var o=e.getAttribute("data-source");t(o),a&&window.history.pushState({type:o},"","#"+o)})}),window.addEventListener("popstate",function(e){e.state&&"type"in e.state&&t(e.state.type)}),a){var s=!r.length;s&&(r=n.video),r in n&&window.history.replaceState({type:r},"",s?"":"#"+r),r!==n.video&&t(r,!0)}}),"plyr.io"===window.location.host&&(!function(e,t,o,i,n,r,a){e.GoogleAnalyticsObject=n,e.ga=e.ga||function(){(e.ga.q=e.ga.q||[]).push(arguments)},e.ga.l=1*new Date,r=t.createElement(o),a=t.getElementsByTagName(o)[0],r.async=1,r.src="//www.google-analytics.com/analytics.js",a.parentNode.insertBefore(r,a)}(window,document,"script",0,"ga"),window.ga("create","UA-40881672-11","auto"),window.ga("send","pageview")); document.addEventListener("DOMContentLoaded",function(){function e(e,t,o){e&&e.classList[o?"add":"remove"](t)}function t(t,a){if(t in n&&(a||t!==r)&&(r.length||t!==n.video)){switch(t){case n.video:o.source={type:"video",title:"View From A Blue Moon",sources:[{src:"https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.mp4",type:"video/mp4"}],poster:"https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.jpg",tracks:[{kind:"captions",label:"English",srclang:"en",src:"https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.en.vtt",default:!0},{kind:"captions",label:"French",srclang:"fr",src:"https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.fr.vtt"}]};break;case n.audio:o.source={type:"audio",title:"Kishi Bashi – “It All Began With A Burst”",sources:[{src:"https://cdn.plyr.io/static/demo/Kishi_Bashi_-_It_All_Began_With_a_Burst.mp3",type:"audio/mp3"},{src:"https://cdn.plyr.io/static/demo/Kishi_Bashi_-_It_All_Began_With_a_Burst.ogg",type:"audio/ogg"}]};break;case n.youtube:o.source={type:"video",title:"View From A Blue Moon",sources:[{src:"https://youtube.com/watch?v=bTqVqk7FSmY",type:"youtube"}]};break;case n.vimeo:o.source={type:"video",sources:[{src:"https://vimeo.com/76979871",type:"vimeo"}]}}r=t,Array.from(i).forEach(function(t){return e(t.parentElement,"active",!1)}),e(document.querySelector('[data-source="'+t+'"]'),"active",!0),Array.from(document.querySelectorAll(".plyr__cite")).forEach(function(e){e.setAttribute("hidden","")}),document.querySelector(".plyr__cite--"+t).removeAttribute("hidden")}}window.shr&&window.shr.setup({count:{classname:"button__count"}});document.addEventListener("focusout",function(e){e.target.classList.remove("tab-focus")}),document.addEventListener("keydown",function(e){9===e.keyCode&&window.setTimeout(function(){document.activeElement.classList.add("tab-focus")},0)});var o=new window.Plyr("#player",{debug:!0,title:"View From A Blue Moon",iconUrl:"../dist/plyr.svg",keyboard:{global:!0},tooltips:{controls:!0},captions:{active:!0},controls:["play-large","play","progress","current-time","mute","volume","captions","settings","fullscreen","pip","airplay"]});window.player=o;var i=document.querySelectorAll("[data-source]"),n={video:"video",audio:"audio",youtube:"youtube",vimeo:"vimeo"},r=window.location.hash.replace("#",""),a=window.history&&window.history.pushState;if(Array.from(i).forEach(function(e){e.addEventListener("click",function(){var o=e.getAttribute("data-source");t(o),a&&window.history.pushState({type:o},"","#"+o)})}),window.addEventListener("popstate",function(e){e.state&&"type"in e.state&&t(e.state.type)}),a){var s=!r.length;s&&(r=n.video),r in n&&window.history.replaceState({type:r},"",s?"":"#"+r),r!==n.video&&t(r,!0)}}),"plyr.io"===window.location.host&&(!function(e,t,o,i,n,r,a){e.GoogleAnalyticsObject=n,e.ga=e.ga||function(){(e.ga.q=e.ga.q||[]).push(arguments)},e.ga.l=1*new Date,r=t.createElement(o),a=t.getElementsByTagName(o)[0],r.async=1,r.src="//www.google-analytics.com/analytics.js",a.parentNode.insertBefore(r,a)}(window,document,"script",0,"ga"),window.ga("create","UA-40881672-11","auto"),window.ga("send","pageview"));
//# sourceMappingURL=demo.js.map //# sourceMappingURL=demo.js.map

File diff suppressed because one or more lines are too long

View File

@ -155,7 +155,7 @@
</aside> </aside>
<!-- Polyfills --> <!-- Polyfills -->
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=es6,Array.prototype.includes,CustomEvent"></script> <script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=es6,Array.prototype.includes,CustomEvent,fetch"></script>
<!-- Plyr core script --> <!-- Plyr core script -->
<script src="../dist/plyr.js"></script> <script src="../dist/plyr.js"></script>

View File

@ -150,7 +150,7 @@ document.addEventListener('DOMContentLoaded', () => {
title: 'View From A Blue Moon', title: 'View From A Blue Moon',
sources: [ sources: [
{ {
src: 'https://www.youtube.com/watch?v=bTqVqk7FSmY', src: 'https://youtube.com/watch?v=bTqVqk7FSmY',
type: 'youtube', type: 'youtube',
}, },
], ],
@ -161,7 +161,6 @@ document.addEventListener('DOMContentLoaded', () => {
case types.vimeo: case types.vimeo:
player.source = { player.source = {
type: 'video', type: 'video',
title: 'View From A Blue Moon',
sources: [ sources: [
{ {
src: 'https://vimeo.com/76979871', src: 'https://vimeo.com/76979871',

2
dist/plyr.js vendored

File diff suppressed because one or more lines are too long

2
dist/plyr.js.map vendored

File diff suppressed because one or more lines are too long

View File

@ -402,7 +402,6 @@ YouTube example:
```javascript ```javascript
player.source = { player.source = {
type: 'video', type: 'video',
title: 'Example title',
sources: [ sources: [
{ {
src: 'bTqVqk7FSmY', src: 'bTqVqk7FSmY',
@ -419,7 +418,6 @@ Vimeo example
```javascript ```javascript
player.source = { player.source = {
type: 'video', type: 'video',
title: 'Example title',
sources: [ sources: [
{ {
src: '143418951', src: '143418951',

View File

@ -65,7 +65,6 @@ const media = {
utils.wrap(this.media, this.elements.wrapper); utils.wrap(this.media, this.elements.wrapper);
} }
// Embeds
if (this.isEmbed) { if (this.isEmbed) {
switch (this.type) { switch (this.type) {
case 'youtube': case 'youtube':
@ -79,9 +78,9 @@ const media = {
default: default:
break; break;
} }
} else {
ui.setTitle.call(this);
} }
ui.setTitle.call(this);
}, },
// Cancel current network requests // Cancel current network requests

View File

@ -56,6 +56,7 @@ const vimeo = {
title: false, title: false,
speed: true, speed: true,
transparent: 0, transparent: 0,
gesture: 'media',
}; };
const params = utils.buildUrlParameters(options); const params = utils.buildUrlParameters(options);
const id = utils.parseVimeoId(player.embedId); const id = utils.parseVimeoId(player.embedId);
@ -203,6 +204,7 @@ const vimeo = {
// Get title // Get title
player.embed.getVideoTitle().then(title => { player.embed.getVideoTitle().then(title => {
player.config.title = title; player.config.title = title;
ui.setTitle.call(this);
}); });
// Get current time // Get current time

View File

@ -23,6 +23,20 @@ const youtube = {
// Set ID // Set ID
this.media.setAttribute('id', utils.generateId(this.type)); this.media.setAttribute('id', utils.generateId(this.type));
// Get the title
const key = 'AIzaSyDrNwtN3nLH_8rjCmu5Wq3ZCm4MNAVdc0c';
const url = `https://www.googleapis.com/youtube/v3/videos?id=${videoId}&fields=items(snippet(title))&part=snippet&key=${key}`;
fetch(url)
.then(response => response.json())
.then(obj => {
if (utils.is.object(obj)) {
this.config.title = obj.items[0].snippet.title;
ui.setTitle.call(this);
}
})
.catch(() => {});
// Setup API // Setup API
if (utils.is.object(window.YT)) { if (utils.is.object(window.YT)) {
youtube.ready.call(this, videoId); youtube.ready.call(this, videoId);

View File

@ -96,11 +96,8 @@ const ui = {
// Ready event at end of execution stack // Ready event at end of execution stack
utils.dispatchEvent.call(this, this.media, 'ready'); utils.dispatchEvent.call(this, this.media, 'ready');
// Autoplay // Set the title
// TODO: check we still need this? ui.setTitle.call(this);
/* if (this.isEmbed && this.config.autoplay) {
this.play();
} */
}, },
// Show the duration on metadataloaded // Show the duration on metadataloaded
@ -137,13 +134,10 @@ const ui = {
} }
// If there's a play button, set label // If there's a play button, set label
if (this.supported.ui) { if (utils.is.nodeList(this.elements.buttons.play)) {
if (utils.is.htmlElement(this.elements.buttons.play)) { Array.from(this.elements.buttons.play).forEach(button => {
this.elements.buttons.play.setAttribute('aria-label', label); button.setAttribute('aria-label', label);
} });
if (utils.is.htmlElement(this.elements.buttons.playLarge)) {
this.elements.buttons.playLarge.setAttribute('aria-label', label);
}
} }
// Set iframe title // Set iframe title

View File

@ -100,12 +100,12 @@ const utils = {
// Load an external SVG sprite // Load an external SVG sprite
loadSprite(url, id) { loadSprite(url, id) {
if (typeof url !== 'string') { if (!utils.is.string(url)) {
return; return;
} }
const prefix = 'cache-'; const prefix = 'cache-';
const hasId = typeof id === 'string'; const hasId = utils.is.string(id);
let isCached = false; let isCached = false;
function updateSprite(data) { function updateSprite(data) {
@ -134,34 +134,25 @@ const utils = {
if (isCached) { if (isCached) {
const data = JSON.parse(cached); const data = JSON.parse(cached);
updateSprite.call(container, data.content); updateSprite.call(container, data.content);
return;
} }
} }
// ReSharper disable once InconsistentNaming // Get the sprite
const xhr = new XMLHttpRequest(); fetch(url)
.then(response => response.text())
.then(text => {
if (support.storage) {
window.localStorage.setItem(
prefix + id,
JSON.stringify({
content: text,
})
);
}
// XHR for Chrome/Firefox/Opera/Safari updateSprite.call(container, text);
if ('withCredentials' in xhr) { });
xhr.open('GET', url, true);
} else {
return;
}
// Once loaded, inject to container and body
xhr.onload = () => {
if (support.storage) {
window.localStorage.setItem(
prefix + id,
JSON.stringify({
content: xhr.responseText,
})
);
}
updateSprite.call(container, xhr.responseText);
};
xhr.send();
} }
}, },