diff --git a/src/youtube-video.ts b/src/youtube-video.ts index f8e3ad6f..606f388a 100644 --- a/src/youtube-video.ts +++ b/src/youtube-video.ts @@ -205,16 +205,19 @@ export class YoutubeVideoElement extends HTMLElement { if (!YoutubeVideoElement.scriptLoadPromise) { YoutubeVideoElement.scriptLoadPromise = new Promise((resolve) => { // NOTE: youtube's iframe api ready only fires once after first script load - if (!window.onYouTubeIframeAPIReady) { - YoutubeVideoElement.triggerYoutubeIframeAPIReady = resolve; - window.onYouTubeIframeAPIReady = () => { - window.onYouTubeIframeAPIReady = null; - // once the script loads once, we are guaranteed for it to - // be ready even after destruction of all instances (if consumer - // doesnt mangle with it) - YoutubeVideoElement.triggerYoutubeIframeAPIReady(); - }; - } + const originalOnYouTubeIframeAPIReady = + window.onYouTubeIframeAPIReady; + YoutubeVideoElement.triggerYoutubeIframeAPIReady = resolve; + window.onYouTubeIframeAPIReady = (...args) => { + window.onYouTubeIframeAPIReady = null; + // once the script loads once, we are guaranteed for it to + // be ready even after destruction of all instances (if consumer + // doesnt mangle with it) + YoutubeVideoElement.triggerYoutubeIframeAPIReady(); + if (originalOnYouTubeIframeAPIReady) { + originalOnYouTubeIframeAPIReady(...args); + } + }; return ResourceManager.loadScript(this.scriptPath); }); } diff --git a/tests/youtube-video-tests.ts b/tests/youtube-video-tests.ts index 8fbafe3d..5ccc62d7 100644 --- a/tests/youtube-video-tests.ts +++ b/tests/youtube-video-tests.ts @@ -67,6 +67,31 @@ describe('Youtube Video Tests', function () { window.YT = origYT; }); + it('does not override original window.onYouTubeIframeAPIReady if exists', async () => { + const onYouTubeIframeAPIReadyStub = sinon.stub(); + Object.defineProperty(window, 'onYouTubeIframeAPIReady', { + get() { + return onYouTubeIframeAPIReadyStub; + }, + configurable: true, + }); + var videoEl = document.createElement( + 'youtube-video' + ) as YoutubeVideoElement; + videoEl.setAttribute('width', '640'); + videoEl.setAttribute('height', '360'); + videoEl.setAttribute( + 'src', + 'http://www.youtube.com/watch?v=nOEw9iiopwI' + ); + testContainer.appendChild(videoEl); + await videoEl.load(); // wait for API to be ready + assert.equal(onYouTubeIframeAPIReadyStub.callCount, 0); + window.onYouTubeIframeAPIReady(); + assert.equal(onYouTubeIframeAPIReadyStub.callCount, 1); + testContainer.removeChild(videoEl); + }); + it('should load proper iFrame player api script when load() is called and remove it from the dom when removed', async function () { var videoEl = document.createElement( 'youtube-video'