3

I have s system where the main content is loaded through ajax, inside a div of the main 'frame'.

In some pages, I need to track when the user finish playing a video. I'm trying to use youtube iframe api. It works ok, but I'm running on some strange things.

The main problem: the actions to happened when the user finishes watching the video are different on each page, and somehow, the API is stacking all the functions and running all at once.

By example, I have the first page, that is loaded through ajax, and have this snippet to load youtube video:

<script>
  // 2. This code loads the IFrame Player API code asynchronously.
  if (window.YT)
  {
    window.YT = undefined;
  }

  var tag = document.createElement('script');

  tag.src = "https://www.youtube.com/iframe_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);


  // 3. This function creates an <iframe> (and YouTube player)
  //    after the API code downloads.
  var player = undefined;
  function onYouTubeIframeAPIReady() {
    player = new YT.Player('divVideo', {
      playerapiid: 'somecode',
      height: '309',
      width: '439',
      videoId: 'somecode',
      events: {
        'onStateChange': onPlayerStateChange
      }
    });
  }

  // 4. The API calls this function when the player's state changes.
  //    The function indicates that when playing a video (state=1),
  //    the player should play for six seconds and then stop.
  function onPlayerStateChange(event) {
    if (event.data == YT.PlayerState.ENDED ) {
     actionToScreen1()
    }
  }

</script>

It works ok. But then, I load the content for my page two, and now the problem begins:

<script>
  // 2. This code loads the IFrame Player API code asynchronously.
  if (window.YT)
  {
    window.YT = undefined;
  }

  var tag = document.createElement('script');

  tag.src = "https://www.youtube.com/iframe_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);


  // 3. This function creates an <iframe> (and YouTube player)
  //    after the API code downloads.
  var player = undefined;
  function onYouTubeIframeAPIReady() {
    player = new YT.Player('divVideo', {
      playerapiid: 'anothercode',
      height: '309',
      width: '439',
      videoId: 'anothercode',
      events: {
    'onStateChange': onPlayerStateChange
      }
    });
  }

  // 4. The API calls this function when the player's state changes.
  //    The function indicates that when playing a video (state=1),
  //    the player should play for six seconds and then stop.
  function onPlayerStateChange(event) {
    if (event.data == YT.PlayerState.ENDED ) {
     actionToScreen2()
    }
  }

</script>

When the video on my screen2 is finished, onPlayerStateChange is called twice, one calling actionToScreen1 and other actionToScreen2. Looks like I'm just loading the container through ajax, the function is stored somewhat globally, but I can't find where, and can't find a way to differentiate which function is being called. How can I fix this?

1
  • Would it perhaps be possible to remove the Screen1 DOM after Screen2 is loaded?
    – Cal McLean
    Apr 5, 2013 at 23:23

2 Answers 2

2

Without looking at your actual page it's hard to tell exactly what scope all your different variables are in, but here's some general advice.

Since you're not completely reloading your web page each time you load in some new content via AJAX, just load the https://www.youtube.com/iframe_api library once, from some "parent" page, instead of trying to delete it and then reload it each time something new is pulled in.

As an extension of that, don't listen for onYouTubeIframeAPIReady events whenever you're pulling in new content. A good pattern to use is to call a method to cue up a video; in that method, if player (set to your YT.Player instance) is defined, then call player.cueVideo()/player.loadVideo(). If player isn't defined yet, then load the https://www.youtube.com/iframe_api library at that point, and define a onYouTubeIframeAPIReady function that will take care of calling the YT.Player constructor with the correct video id once the library is loaded.

Here's an example of some JavaScript code that does pretty much that: https://code.google.com/p/youtube-direct-lite/source/browse/static/js/ytdl/player.js It uses RequireJS modules, so the syntax is a little different than what you're doing, but the general idea is the same. You would call that code from an external JS file that uses the module via player.playVideo(containerDiv, videoId)

1

After trying all kinds of solutions, I gave up, and used a perfect workaround.

<iframe id="video-recorder" src="/site/recorder" scrolling="no"
            style="width: 400px; height: 260px; overflow: hidden;">
</iframe>

The iframe will take care of the reloading of api and everything..

This is in the iframe. Make sure you have the same size, so that all is visible:

<!doctype html><html><head>
<meta charset="utf-8">
<style>html,body { margin: 0; padding: 0; overflow: hidden; width: 400px; height: 260px; }</style>
<script src="http://www.youtube.com/iframe_api"></script>
<body>
    <div id="widget"></div>
    <div id="player"></div>

<script>
var widget;
var player;

function onYouTubeIframeAPIReady() {
    widget = new YT.UploadWidget('widget', {
        width: 400,
        height: 260,
        events: {
            'onUploadSuccess': onUploadSuccess,
            'onProcessingComplete': onProcessingComplete
        }
    });
}

The rest of the code, like events, etc, can be found on official page: https://developers.google.com/youtube/youtube_upload_widget

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.