3

I've got an odd problem here.

My web page calls for YouTube API when the video is embedded, and attaches a variable to the API. I can use the API functions perfectly fine when I refresh the page, or go to the page initially. If the page is accessed again without refreshing the whole website, I get an error saying player is null.

Uncaught TypeError: Cannot read property 'seekTo' of null 

I tried to debug, and when I attached a console.log to onYouTubeIframeAPIReady, it doesn't print anything the second time and on. It seems like the event isn't attaching when the page is loaded without reloading the whole site.

To combat this, I tried to "unload" the javascript by removing the script tag. It doesn't work.

I've tried to use this method: YouTube iframe API: how do I control a iframe player that's already in the HTML?

It works great to play videos, but I can't figure out how to do seekTo(). I've tried callPlayer('player','seekTo','30',true) and all the other variants of 30, true, '30', 'true', etc.

  <div class="flex-video <% if @video.ws == 1 %><%= 'widescreen' %><% end %>">
    <iframe id="player" width="640" height="480"
    src="https://www.youtube.com/embed/<%= @video.youtube_id %>?modestbranding=1&theme=light&enablejsapi=1&"
    frameborder="0" allowfullscreen></iframe>
  </div>

  <script type="text/javascript">
  (function () {
    $('#youtubeapi').remove();
    var d = new Date();
    var n = d.getTime();
    var tag = document.createElement('script');
    tag.setAttribute("id", "youtubeapi");
    tag.src = "https://www.youtube.com/iframe_api?" +n;
    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 = null;
      function onYouTubeIframeAPIReady() {
        player = new YT.Player('player', {
          events: {
          }
        });
      }

      (function() {

      })();
      </script>
    </div>
Community
  • 1
  • 1
dzjin
  • 67
  • 8

0 Answers0