Skip to content

Commit

Permalink
fix: made ad stop when user leaves page and start when tab is active …
Browse files Browse the repository at this point in the history
…again, plus made sure video is paused if ad is playing
  • Loading branch information
malmen237 committed Jun 14, 2024
1 parent 0cd8448 commit 2736135
Showing 1 changed file with 20 additions and 7 deletions.
27 changes: 20 additions & 7 deletions packages/demo/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -223,12 +223,6 @@ async function main() {
* Loads the video content and initializes IMA ad playback.
*/
async function playAds() {
// Initialize the container. Must be done through a user action on mobile
// devices.
const player = new WebPlayer({
video: video
});

adDisplayContainer.initialize();

try {
Expand Down Expand Up @@ -259,7 +253,7 @@ async function main() {
);

// Add listeners to the required events.
adsManager.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, onAdError);
adsManager.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, onAdError());
adsManager.addEventListener(
google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED,
onContentPauseRequested
Expand Down Expand Up @@ -343,6 +337,22 @@ async function main() {
// setupUIForAds();
}

// Handle page visibility change events, so add is paused when user is redirected,
// and when the user returns the ad resumes playing
document.addEventListener('visibilitychange', function() {
if (document.hidden) {
if (isAdPlaying) {
adsManager.pause();
isAdPlaying = false;
}
} else {
if (!isAdPlaying && adsManager) {
adsManager.resume();
isAdPlaying = true;
}
}
});

/**
* Resumes video content and removes ad UI.
*/
Expand All @@ -363,6 +373,9 @@ async function main() {
event.preventDefault();
event.stopImmediatePropagation();

if (isAdPlaying) {
video.pause();
}
playAds();
}, true);

Expand Down

0 comments on commit 2736135

Please sign in to comment.