DEV Community

Cover image for Youtube iFrame API - YT.Player is not a constructor
Sung M. Kim
Sung M. Kim

Posted on • Originally published at sung.codes on

Youtube iFrame API - YT.Player is not a constructor

As I was playing around with YouTube Player API Reference for iframe Embeds, I was getting the following error,

TypeError

YT.Player is not a constructor

The error occurred when I was creating a new YT.Player instance.

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

I was looking at this reply for the question, Uncaught TypeError: YT.Player is not a constructor but it didn't really answer what the "fix" is.

After some digging I found a working CodeSandbox sandbox, https://codesandbox.io/s/youtube-iframe-api-tpjwj (this uses jQuery), which used a undocumented API, YT.ready().

It seems to wait until the player instance is "ready" to be created similar to DOMContentLoaded for DOM.

So the fix it to wait within the callback of YT.ready.

function setupPlayer() {
    /**
     * THIS FAILS!!!!!
     */
    // player = new YT.Player("player", {
    // height: "390",
    // width: "640",
    // videoId: "M7lc1UVf-VE",
    // events: {
    // onReady: onPlayerReady,
    // onStateChange: onPlayerStateChange
    // }
    // });

    /**
     * Need to wait until Youtube Player is ready!
     */
    window.YT.ready(function() {
      player = new window.YT.Player("video", {
        height: "390",
        width: "640",
        videoId: "M7lc1UVf-VE",
        events: {
          onReady: onPlayerReady,
          onStateChange: onPlayerStateChange
        }
      });
    });
  }

The working Sandbox (I converted the jQuery version to Vanillia JS) - https://codesandbox.io/s/soanswer52062169-mem83?file=/src/index.js:406-1242


Image by SplitShire from Pixabay

Top comments (2)

Collapse
 
eduardonwa profile image
Eduardo Cookie Lifter

Hi, im just searching the web looking on how to use this API with my channel. Goal is to display my own videos enabling the iframe/player object. If you can do this please share! Thanks.

Collapse
 
zahardoc profile image
Sergey Zaharchenko

Thank you so much!