0

I have a website with a custom audio recording when trying to leave the site. This is working fine, but the issue is that I also have a YouTube video that overlaps my audio.

I want to pause or mute my YouTube video when my audio starts playing, this is triggered by window.onbeforeunload

I tried to do so like this:

window.onbeforeunload = function () {
         player.pauseVideo();
       }

I already implemented the YouTube API and everything is working fine, but the pause is not being triggered. Any idea why?

Thanks!

2 Answers2

0

Start from YouTube Player API Reference for iframe Embeds.

Then you can follow these steps from an SO post.

  1. The asynchronous code snippet downloads and executes the YT iframe API
  2. onYouTubeIframeAPIReady() is fired when the API is ready
  3. Create a new YT.Player object
  4. Your code can now call pauseVideo() on your player object

You will most likely want to disable any events on your img until onYouTubeIframeAPIReady() has been fired.

Refer also to this code for reference.

MαπμQμαπkγVπ.0
  • 5,887
  • 1
  • 27
  • 65
0

AS the YouTube api is an asynchronous load, you can not call it from anything that has already executed.

My suggestion would be to put a "var" of "audio_playing" into your window.onbeforeunload function and make it global. Then set it to true or false respectively.

In your YT api code. have the YT player look for that "var" and set the play state accordingly.

Tempus
  • 787
  • 1
  • 8
  • 18