How do I get the reference to an existing YouTube player?

后端 未结 5 632
忘掉有多难
忘掉有多难 2020-12-05 18:05

I have a few qu

相关标签:
5条回答
  • 2020-12-05 18:14

    The best answer is almost right. You have to place "enablejsapi=1" on the iframe src. Something like:

    <iframe id="youtube-video" width="560" height="315" 
            src="https://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1" frameborder="0" 
            allowfullscreen>
    </iframe>
    
    0 讨论(0)
  • 2020-12-05 18:26

    Maximus S gave a perfectly correct answer. The official YouTube IFrame Player API docs suggest initialising the player through a unique id of an iframe with the video as var yPlayer = new YT.Player('unique-id');.

    For the future readers of this question looking for a way to generate a YouTube Player from a reference to an iframe element without id (as myself), it is possible to do so by running var yPlayer = new YT.Player(iframeElement); if you add type="text/html" attribute to the iframe element and set enablejsapi=1 parameter in the src attribute:

    <iframe type="text/html" height="360" width="640" src="https://www.youtube.com/embed/jNQXAC9IVRw?enablejsapi=1"></iframe>

    Full snippet

    0 讨论(0)
  • 2020-12-05 18:28

    This can be done like the following.

    Given a general YouTube embed source code:

    <iframe width="560" height="315" src="//www.youtube.com/embed/M7lc1UVf-VE" frameborder="0" allowfullscreen></iframe>
    

    a. Add a enablejsapi query param and set it to 1 in the src URL

    <iframe width="560" height="315" src="//www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1" frameborder="0" allowfullscreen></iframe>
    

    b. Give it a unique id

    <iframe id="youtube-video" width="560" height="315" src="//www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1" frameborder="0" allowfullscreen></iframe>
    

    c. Load YouTube iFrame API

    <script src="https://www.youtube.com/iframe_api"></script>
    

    d. Create a player that references the existing iFrame

    var player;
    function onYouTubeIframeAPIReady() {
      player = new YT.Player('youtube-video', {
        events: {
          'onReady': onPlayerReady,
          'onStateChange': onPlayerStateChange
        }
      });
    }
    
    function onPlayerReady() {
      console.log("hey Im ready");
      //do whatever you want here. Like, player.playVideo();
    
    }
    
    function onPlayerStateChange() {
      console.log("my state changed");
    }
    
    0 讨论(0)
  • 2020-12-05 18:33
    var player = YT.get('id-of-youtube-iframe');
    
    0 讨论(0)
  • 2020-12-05 18:33

    A great way to do this without loading the IFrame API in the parent window is to grab the object from the IFrame

    var ytplayer_window = document.getElementById("playerIFrame").contentWindow;
    var player = ytplayer_window.yt.player.getPlayerByElement(ytplayer_window.player);
    
    0 讨论(0)
提交回复
热议问题