fix blocking play() if ads are set

This commit is contained in:
ferdiemmen 2018-01-15 23:30:54 +01:00
parent c24c05226d
commit 1cef48d4f8
6 changed files with 53 additions and 53 deletions

2
demo/dist/demo.js vendored
View File

@ -1,3 +1,3 @@
document.addEventListener("DOMContentLoaded",function(){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 e=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},keys:{google:"AIzaSyDrNwtN3nLH_8rjCmu5Wq3ZCm4MNAVdc0c"},ads:{tagUrl:"http://go.aniview.com/api/adserver6/vast/?AV_PUBLISHERID=58c25bb0073ef448b1087ad6&AV_CHANNELID=5a0458dc28a06145e4519d21&AV_URL=127.0.0.1:3000&cb=1&AV_WIDTH=640&AV_HEIGHT=480"}});window.player=e;var t=document.querySelectorAll("[data-source]"),o={video:"video",audio:"audio",youtube:"youtube",vimeo:"vimeo"},i=window.location.hash.replace("#",""),a=window.history&&window.history.pushState;function r(e,t,o){e&&e.classList[o?"add":"remove"](t)}function n(a,n){if(a in o&&(n||a!==i)&&(i.length||a!==o.video)){switch(a){case o.video:e.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 o.audio:e.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 o.youtube:e.source={type:"video",title:"View From A Blue Moon",sources:[{src:"https://youtube.com/watch?v=bTqVqk7FSmY",provider:"youtube"}]};break;case o.vimeo:e.source={type:"video",sources:[{src:"https://vimeo.com/76979871",provider:"vimeo"}]}}i=a,Array.from(t).forEach(function(e){return r(e.parentElement,"active",!1)}),r(document.querySelector('[data-source="'+a+'"]'),"active",!0),Array.from(document.querySelectorAll(".plyr__cite")).forEach(function(e){e.setAttribute("hidden","")}),document.querySelector(".plyr__cite--"+a).removeAttribute("hidden")}}if(Array.from(t).forEach(function(e){e.addEventListener("click",function(){var t=e.getAttribute("data-source");n(t),a&&window.history.pushState({type:t},"","#"+t)})}),window.addEventListener("popstate",function(e){e.state&&"type"in e.state&&n(e.state.type)}),a){var s=!i.length;s&&(i=o.video),i in o&&window.history.replaceState({type:i},"",s?"":"#"+i),i!==o.video&&n(i,!0)}}),"plyr.io"===window.location.host&&(!function(e,t,o,i,a,r,n){e.GoogleAnalyticsObject="ga",e.ga=e.ga||function(){(e.ga.q=e.ga.q||[]).push(arguments)},e.ga.l=1*new Date,r=t.createElement("script"),n=t.getElementsByTagName("script")[0],r.async=1,r.src="//www.google-analytics.com/analytics.js",n.parentNode.insertBefore(r,n)}(window,document),window.ga("create","UA-40881672-11","auto"),window.ga("send","pageview"));
document.addEventListener("DOMContentLoaded",function(){window.shr&&window.shr.setup({count:{classname:"button__count"}});var e="tab-focus";document.addEventListener("focusout",function(t){t.target.classList.remove(e)}),document.addEventListener("keydown",function(t){9===t.keyCode&&window.setTimeout(function(){document.activeElement.classList.add(e)},0)});var t=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},keys:{google:"AIzaSyDrNwtN3nLH_8rjCmu5Wq3ZCm4MNAVdc0c"},ads:{tagUrl:"https://pubads.g.doubleclick.net/gampad/ads?sz=640x480&iu=/124319096/external/ad_rule_samples&ciu_szs=300x250&ad_rule=1&impl=s&gdfp_req=1&env=vp&output=vmap&unviewed_position_start=1&cust_params=deployment%3Ddevsite%26sample_ar%3Dpremidpostoptimizedpod&cmsid=496&vid=short_onecue&correlator="}});window.player=t;var o=document.querySelectorAll("[data-source]"),i={video:"video",audio:"audio",youtube:"youtube",vimeo:"vimeo"},r=window.location.hash.replace("#",""),a=window.history&&window.history.pushState;function n(e,t,o){e&&e.classList[o?"add":"remove"](t)}function s(e,a){if(e in i&&(a||e!==r)&&(r.length||e!==i.video)){switch(e){case i.video:t.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 i.audio:t.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 i.youtube:t.source={type:"video",title:"View From A Blue Moon",sources:[{src:"https://youtube.com/watch?v=bTqVqk7FSmY",provider:"youtube"}]};break;case i.vimeo:t.source={type:"video",sources:[{src:"https://vimeo.com/76979871",provider:"vimeo"}]}}r=e,Array.from(o).forEach(function(e){return n(e.parentElement,"active",!1)}),n(document.querySelector('[data-source="'+e+'"]'),"active",!0),Array.from(document.querySelectorAll(".plyr__cite")).forEach(function(e){e.setAttribute("hidden","")}),document.querySelector(".plyr__cite--"+e).removeAttribute("hidden")}}if(Array.from(o).forEach(function(e){e.addEventListener("click",function(){var t=e.getAttribute("data-source");s(t),a&&window.history.pushState({type:t},"","#"+t)})}),window.addEventListener("popstate",function(e){e.state&&"type"in e.state&&s(e.state.type)}),a){var c=!r.length;c&&(r=i.video),r in i&&window.history.replaceState({type:r},"",c?"":"#"+r),r!==i.video&&s(r,!0)}}),"plyr.io"===window.location.host&&(!function(e,t,o,i,r,a,n){e.GoogleAnalyticsObject=r,e.ga=e.ga||function(){(e.ga.q=e.ga.q||[]).push(arguments)},e.ga.l=1*new Date,a=t.createElement(o),n=t.getElementsByTagName(o)[0],a.async=1,a.src="//www.google-analytics.com/analytics.js",n.parentNode.insertBefore(a,n)}(window,document,"script",0,"ga"),window.ga("create","UA-40881672-11","auto"),window.ga("send","pageview"));
//# sourceMappingURL=demo.js.map

File diff suppressed because one or more lines are too long

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

@ -41,14 +41,14 @@ export default class Ads {
this.time = Date.now();
this.startEvents = getStartEvents();
this.adDisplayContainer = null;
this.adDisplayElement = null;
this.adsDisplayElement = null;
this.adsManager = null;
this.adsLoader = null;
this.adsCuePoints = null;
this.currentAd = null;
this.events = {};
this.safetyTimer = null;
this.videoElement = document.createElement('video');
this.playing = false;
// Setup a simple promise to resolve if the IMA loader is ready.
this.adsLoaderResolve = () => {};
@ -89,17 +89,17 @@ export default class Ads {
const { container } = this.player.elements;
// Create ads loader.
this.adsLoader = new window.google.ima.AdsLoader(this.adDisplayContainer, this.videoElement);
this.adsLoader = new google.ima.AdsLoader(this.adDisplayContainer);
// Tell the adsLoader we are handling ad breaks manually.
this.adsLoader.getSettings().setAutoPlayAdBreaks(false);
// Listen and respond to ads loaded and error events.
this.adsLoader.addEventListener(window.google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED, event => this.onAdsManagerLoaded(event), false);
this.adsLoader.addEventListener(window.google.ima.AdErrorEvent.Type.AD_ERROR, error => this.onAdError(error), false);
this.adsLoader.addEventListener(google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED, event => this.onAdsManagerLoaded(event), false);
this.adsLoader.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, error => this.onAdError(error), false);
// Request video ads.
const adsRequest = new window.google.ima.AdsRequest();
const adsRequest = new google.ima.AdsRequest();
adsRequest.adTagUrl = this.player.config.ads.tagUrl;
// Specify the linear and nonlinear slot sizes. This helps the SDK to
@ -115,31 +115,32 @@ export default class Ads {
}
onAdsManagerLoaded(adsManagerLoadedEvent) {
const { videoElement } = this;
// Get the ads manager.
const settings = new window.google.ima.AdsRenderingSettings();
settings.restoreCustomPlaybackStateOnAdBreakComplete = true;
const settings = new google.ima.AdsRenderingSettings();
// Tell the SDK NOT to save and restore content video state on our behalf.
settings.restoreCustomPlaybackStateOnAdBreakComplete = false;
settings.enablePreloading = true;
// The SDK is polling currentTime on the contentPlayback. And needs a duration
// so it can determine when to start the mid- and post-roll.
this.adsManager = adsManagerLoadedEvent.getAdsManager(videoElement, settings);
this.adsManager = adsManagerLoadedEvent.getAdsManager(this.player, settings);
// Get the cue points for any mid-rolls by filtering out the pre- and post-roll.
this.adsCuePoints = this.adsManager.getCuePoints().filter(x => x > 0 && x !== -1);
// Add listeners to the required events.
this.adsManager.addEventListener(window.google.ima.AdErrorEvent.Type.AD_ERROR, error => this.onAdError(error));
this.adsManager.addEventListener(window.google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED, event => this.onAdEvent(event));
this.adsManager.addEventListener(window.google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED, event => this.onAdEvent(event));
this.adsManager.addEventListener(window.google.ima.AdEvent.Type.ALL_ADS_COMPLETED, event => this.onAdEvent(event));
this.adsManager.addEventListener(window.google.ima.AdEvent.Type.AD_BREAK_READY, event => this.onAdEvent(event));
this.adsManager.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, error => this.onAdError(error));
this.adsManager.addEventListener(google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED, event => this.onAdEvent(event));
this.adsManager.addEventListener(google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED, event => this.onAdEvent(event));
this.adsManager.addEventListener(google.ima.AdEvent.Type.ALL_ADS_COMPLETED, event => this.onAdEvent(event));
this.adsManager.addEventListener(google.ima.AdEvent.Type.AD_BREAK_READY, event => this.onAdEvent(event));
// Listen to any additional events, if necessary.
this.adsManager.addEventListener(window.google.ima.AdEvent.Type.LOADED, event => this.onAdEvent(event));
this.adsManager.addEventListener(window.google.ima.AdEvent.Type.STARTED, event => this.onAdEvent(event));
this.adsManager.addEventListener(window.google.ima.AdEvent.Type.COMPLETE, event => this.onAdEvent(event));
this.adsManager.addEventListener(google.ima.AdEvent.Type.LOADED, event => this.onAdEvent(event));
this.adsManager.addEventListener(google.ima.AdEvent.Type.STARTED, event => this.onAdEvent(event));
this.adsManager.addEventListener(google.ima.AdEvent.Type.COMPLETE, event => this.onAdEvent(event));
// Resolve our adsManager.
this.adsManagerResolve();
@ -164,12 +165,9 @@ export default class Ads {
// This event indicates that a mid-roll ad is ready to start.
// We pause the player and tell the adsManager to start playing the ad.
this.player.debug.log(`[${(Date.now() - this.time) / 1000}s][IMA SDK] AD_BREAK_READY |`, 'Fired when an ad rule or a VMAP ad break would have played if autoPlayAdBreaks is false.');
this.player.pause();
this.adsManager.start();
this.handleEventListeners('AD_BREAK_READY');
this.adsManager.start();
this.playing = true;
break;
case google.ima.AdEvent.Type.AD_METADATA:
this.player.debug.log(`[${(Date.now() - this.time) / 1000}s][IMA SDK] AD_METADATA |`, 'Fired when an ads list is loaded.');
@ -187,35 +185,33 @@ export default class Ads {
// remaining time detection.
// clearInterval(intervalTimer);
this.player.debug.log(`[${(Date.now() - this.time) / 1000}s][IMA SDK] COMPLETE |`, 'Fired when the ad completes playing.');
this.handleEventListeners('COMPLETE');
this.adDisplayElement.style.display = 'none';
this.adsDisplayElement.style.display = 'none';
this.playing = false;
if (this.player.currentTime < this.player.duration) {
this.player.play();
}
break;
case window.google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED:
case google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED:
this.player.debug.log(`[${(Date.now() - this.time) / 1000}s][IMA SDK] CONTENT_PAUSE_REQUESTED |`, 'Fired when content should be paused. This usually happens right before an ad is about to cover the content.');
this.player.pause();
this.handleEventListeners('CONTENT_PAUSE_REQUESTED');
break;
case window.google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED:
case google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED:
this.player.debug.log(`[${(Date.now() - this.time) / 1000}s][IMA SDK] CONTENT_RESUME_REQUESTED |`, 'Fired when content should be resumed. This usually happens when an ad finishes or collapses.');
this.handleEventListeners('CONTENT_RESUME_REQUESTED');
break;
case google.ima.AdEvent.Type.LOADED:
// This is the first event sent for an ad - it is possible to
// determine whether the ad is a video ad or an overlay.
this.player.debug.log(`[${(Date.now() - this.time) / 1000}s][IMA SDK] LOADED |`, event.getAd().getContentType());
this.handleEventListeners('LOADED');
// Show the ad display element.
this.adDisplayElement.style.display = 'block';
this.handleEventListeners('LOADED');
this.adsDisplayElement.style.display = 'block';
if (!ad.isLinear()) {
// Position AdDisplayContainer correctly for overlay.
@ -231,8 +227,8 @@ export default class Ads {
// can adjust the UI, for example display a pause button and
// remaining time.
this.player.debug.log(`[${(Date.now() - this.time) / 1000}s][IMA SDK] STARTED |`, 'Fired when the ad starts playing.');
this.player.pause();
this.playing = true;
this.handleEventListeners('STARTED');
break;
case google.ima.AdEvent.Type.DURATION_CHANGE:
@ -302,7 +298,7 @@ export default class Ads {
this.player.debug.warn(`[${(Date.now() - this.time) / 1000}s][IMA SDK]`, 'Advertisement cancelled.');
// Todo: Removing the ad container might be problematic if we were to recreate the adsManager. Think of playlists. Every new video you need to request a new VAST xml and preload the advertisement.
this.adDisplayElement.remove();
this.adsDisplayElement.remove();
// Tell our adsManager to go bye bye.
this.adsManagerPromise.then(() => {
@ -324,16 +320,16 @@ export default class Ads {
// We assume the adContainer is the video container of the plyr element
// that will house the ads.
this.adDisplayContainer = new window.google.ima.AdDisplayContainer(container);
this.adDisplayContainer = new google.ima.AdDisplayContainer(container);
this.adDisplayElement = container.firstChild;
this.adsDisplayElement = container.firstChild;
// The AdDisplayContainer call from google IMA sets the style attribute
// by default. We remove the inline style and set it through the stylesheet.
this.adDisplayElement.removeAttribute('style');
this.adsDisplayElement.removeAttribute('style');
// Set class name on the adDisplayContainer element.
this.adDisplayElement.setAttribute('class', this.player.config.classNames.ads);
this.adsDisplayElement.setAttribute('class', this.player.config.classNames.ads);
// Play ads when clicked. Wait until the adsManager and adsLoader
// are both resolved.
@ -341,7 +337,7 @@ export default class Ads {
this.adsManagerPromise,
this.adsLoaderPromise,
]).then(() => {
this.setOnClickHandler(this.adDisplayElement, this.playAds);
this.setOnClickHandler(this.adsDisplayElement, this.playAds);
});
}
@ -355,7 +351,7 @@ export default class Ads {
try {
// Initialize the ads manager. Ad rules playlist will start at this time.
this.adsManager.init(container.offsetWidth, container.offsetHeight, window.google.ima.ViewMode.NORMAL);
this.adsManager.init(container.offsetWidth, container.offsetHeight, google.ima.ViewMode.NORMAL);
// Call play to start showing the ad. Single video and overlay ads will
// start at this time; the call will be ignored for ad rules.
@ -363,7 +359,7 @@ export default class Ads {
} catch (adError) {
// An error may be thrown if there was a problem with the VAST response.
this.player.play();
this.adDisplayElement.remove();
this.adsDisplayElement.remove();
if (this.player.debug) {
throw new Error(adError);
@ -372,6 +368,10 @@ export default class Ads {
});
}
isPlaying() {
return this.playing;
}
/**
* Setup hooks for Plyr and window events. This ensures
* the mid- and post-roll launch at the correct time. And
@ -386,18 +386,13 @@ export default class Ads {
this.adsLoader.contentComplete();
});
this.player.on('timeupdate', event => {
const { currentTime } = event.detail.plyr;
this.videoElement.currentTime = Math.ceil(currentTime);
});
this.player.on('seeking', event => {
time = event.detail.plyr.currentTime;
time = this.player.currentTime;
return time;
});
this.player.on('seeked', event => {
const seekedTime = event.detail.plyr.currentTime;
const seekedTime = this.player.currentTime;
this.adsCuePoints.forEach((cuePoint, index) => {
if (time < cuePoint && cuePoint < seekedTime) {
@ -409,7 +404,7 @@ export default class Ads {
// Listen to the resizing of the window. And resize ad accordingly.
window.addEventListener('resize', () => {
this.adsManager.resize(container.offsetWidth, container.offsetHeight, window.google.ima.ViewMode.NORMAL);
this.adsManager.resize(container.offsetWidth, container.offsetHeight, google.ima.ViewMode.NORMAL);
});
}

View File

@ -309,6 +309,11 @@ class Plyr {
* Play the media
*/
play() {
if (this.ads) {
this.ads.playAds();
return this;
}
return this.media.play();
}