Skip to content

Commit

Permalink
Automatically close video trailer overlay when video ends when 'enabl…
Browse files Browse the repository at this point in the history
…e_trailers: true' is used
  • Loading branch information
mkanet committed Jun 24, 2024
1 parent a10e795 commit a02958c
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
2 changes: 1 addition & 1 deletion VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
0.5.8
0.5.9
26 changes: 25 additions & 1 deletion upcoming-media-card.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,25 @@ class UpcomingMediaCard extends HTMLElement {
iframeContainer.style.maxWidth = '1600px';
iframeContainer.style.maxHeight = '900px';
iframeContainer.style.position = 'relative';
let checkVideoEndedInterval;
const closeOverlayAndCleanup = () => {
clearInterval(checkVideoEndedInterval);
window.removeEventListener('message', handleMessage);
closeOverlay();
};
const handleMessage = (event) => {
if (event.source === iframe.contentWindow) {
try {
const data = JSON.parse(event.data);
if (data.event === 'infoDelivery' && data.info && data.info.playerState === 0) {
closeOverlayAndCleanup();
}
} catch (e) {
console.error('Error parsing message:', e);
}
}
};
window.addEventListener('message', handleMessage);
const closeButton = document.createElement('button');
closeButton.innerHTML = '×';
closeButton.style.position = 'absolute';
Expand Down Expand Up @@ -86,14 +105,19 @@ class UpcomingMediaCard extends HTMLElement {
const iframe = document.createElement('iframe');
iframe.style.width = '100%';
iframe.style.height = '100%';
iframe.src = `https://www.youtube.com/embed/${videoId}?autoplay=1&controls=1&rel=0&fs=1&modestbranding=1`;
iframe.src = `https://www.youtube.com/embed/${videoId}?autoplay=1&controls=1&rel=0&fs=1&modestbranding=1&enablejsapi=1`;
iframe.frameBorder = '0';
iframe.allow = 'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture';
iframe.allowFullscreen = true;
checkVideoEndedInterval = setInterval(() => {
iframe.contentWindow.postMessage('{"event":"listening"}', '*');
}, 1000);
iframeContainer.appendChild(iframe);
iframeContainer.appendChild(closeButton);
overlay.appendChild(iframeContainer);
const closeOverlay = () => {
clearInterval(checkVideoEndedInterval);
window.removeEventListener('message', handleMessage);
document.body.removeChild(overlay);
document.body.style.overflow = '';
};
Expand Down

0 comments on commit a02958c

Please sign in to comment.