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

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

I have a few qu

5条回答
  •  -上瘾入骨i
    2020-12-05 18:28

    This can be done like the following.

    Given a general YouTube embed source code:

    
    

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

    
    

    b. Give it a unique id

    
    

    c. Load YouTube iFrame API

    
    

    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");
    }
    

提交回复
热议问题