YouTube iframe API: how do I control an iframe player that's already in the HTML?

前端 未结 5 1354
[愿得一人]
[愿得一人] 2020-11-22 08:00

I want to be able to control iframe based YouTube players. This players will be already in the HTML, but I want to control them via the JavaScript API.

I\'ve been re

5条回答
  •  盖世英雄少女心
    2020-11-22 08:28

    Looks like YouTube has updated their JS API so this is available by default! You can use an existing YouTube iframe's ID...

    
    

    ...in your JS...

    var player;
    function onYouTubeIframeAPIReady() {
      player = new YT.Player('player', {
        events: {
          'onStateChange': onPlayerStateChange
        }
      });
    }
    
    function onPlayerStateChange() {
      //...
    }
    

    ...and the constructor will use your existing iframe instead of replacing it with a new one. This also means you don't have to specify the videoId to the constructor.

    See Loading a video player

提交回复
热议问题