0

The docs say we should use a div container where the <iframe> element will be appended.

That works:

new YT.Player('player', {
   height: '390',
   width: '640',
   videoId: 'M7lc1UVf-VE',
   events: {
      onReady: onPlayerReady,
      onStateChange: onPlayerStateChange
   }
});

But I should have an element <div id="player"></div> on the page.

Is it possible that if I already have the iframe element with the embedded video to use that iframe in the YT.Player constructor?

I would like to have something like this:

new YT.Player('iframeId').playVideo();

But the playVideo isn't there because the player is not loading (I guess that's happening because we are providing the iframe id).

Is there a way to connect an existing iframe with the YT.Player instance?

Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474

1 Answers1

0

I wrote a quick hack for it: get the video id from the <iframe> url, replace the iframe with a div and initialize the player:

YTPlayerIframe = (function () {
  function youtube_parser(url){
     var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
     var match = url.match(regExp);
     return (match&&match[7].length==11)? match[7] : false;
  }
  var __oldPlayer = YT.Player;
  var player = function (id, options) {
    var el = document.getElementById(id);
    options.videoId = youtube_parser(el.getAttribute("src"))
    el.outerHTML = "<div id='" + id + "'>test</div>";
    return new __oldPlayer(id, options);
  };
  return player;
})();

Then you can use it this way:

var myPlayer = YTPlayerIframe("iframe-id", {
   // The videoId option will be taken from the iframe src.
   events: {
      onReady: function () {...}
   }
});
Community
  • 1
  • 1
Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474