YouTube API — not firing 'onYouTubePlayerReady

2019-04-18 12:23发布

From what I've read, this is how I should setup the YouTube API:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta content='text/html;charset=UTF-8' http-equiv='content-type' />
    <title>Youtube Player</title>
    <script src="jquery.js" type="text/javascript"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js" type="text/javascript"></script>
    <script type="text/javascript" charset="utf-8">
      function onYouTubePlayerReady(id) {
        console.log("onYouTubePlayerReady() Fired!");
        var player = $("#youtube_player").get(0);
      }

      var params = { allowScriptAccess: "always" };
      var atts = { id: "youtube_player" };
      swfobject.embedSWF("http://www.youtube.com/apiplayer?enablejsapi=1", 
                         "youtube", "425", "356", "8", null, null, params, atts);

    </script>
  </head>
  <body>
    <div id="youtube"></div>
  </body>
</html>

However, 'onYouTubePlayerReady()' doesn't fire at all, and if I manually get a reference to the player, a lot of methods are undefined; for example, cueVideoById() works, but playVideo() doesn't.

How can I fix this problem?

7条回答
爷、活的狠高调
2楼-- · 2019-04-18 13:00

If you're embedding youtube videos like so:

<iframe src="http://www.youtube.com/embed/VIDEO_ID?jsapi=1" width="1280" height="720" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>

then you should place

<script src="http://www.youtube.com/player_api"></script>

after the </iframe>. At least that's how I got it to work.

Additionally, if you're dynamically changing the [src] attribute of the iframe via jQuery or whatever to load a new video then you need to call onYouTubePlayerAPIReady() after it has loaded.

I prefer to change the [src] attribute and then: setTimeout(onYouTubePlayerAPIReady, 500);

查看更多
登录 后发表回答