YouTube IFrame Player API abstraction.

YouTube Player

youtube-player is an abstraction of YouTube IFrame Player API (YIPA).

The downsides of using YouTube IFrame Player API are:

  • Requires to define callbacks in the global scope (window).
  • Requires to track the state of a player (e.g. you must ensure that video player is "ready" before you can use the API).


  • Registers listeners required to establish when YIPA has been loaded.
  • Does not overwrite global YIPA callback functions.
  • Queues player API calls until when video player is "ready".
 * @typedef options
 * @see
 * @param {Number} width
 * @param {Number} height
 * @param {String} videoId
 * @param {Object} playerVars
 * @param {Object} events
 * A factory function used to produce an instance of YT.Player and queue function calls and proxy events of the resulting object.
 * @param {HTMLElement|String} elementId Either the DOM element or the id of the HTML element where the API will insert an <iframe>.
 * @param {player~options} options
 * @return {Object}
import YouTubePlayer from 'youtube-player';

youtube-player is a factory function.

The resulting object exposes all functions of an instance of YT.Player. The difference is that the function body is wrapped in a promise. This promise is resolved only when the player has finished loading and is ready to begin receiving API calls (onReady). Therefore, all function calls are queued and replayed only when player is ready.

This encapsulation does not affect the API other than making every function return a promise.

let player;
player = YouTubePlayer('video-player');
// 'loadVideoById' is queued until the player is ready to receive API calls. 
// 'playVideo' is queue until the player is ready to received API calls and after 'loadVideoById' has been called. 
// 'stopVideo' is queued after 'playVideo'. 
    .then(() => {
        // Every function returns a promise that is resolved after the target function has been executed. 

player.on event emitter is used to listen to all YouTube IFrame Player API events, e.g.

player.on('stateChange', (event) => {

Using Bower:

bower install youtube-player

Using NPM:

npm install youtube-player

When using the browser distribution (./dist/browser/youtube-player.js) youtube-player is available under window.gajus.YouTubePlayer namespace.

<!DOCTYPE html>
    <script src='./bower_components/youtube-player/dist/youtube-player.js'></script> 
    <div id='my-player'></div>
    var YouTubePlayer = window.gajus.YouTubePlayer;
npm install webpack-dev-server -g

This will start a HTTP server on port 8000.

Version ~0 of the youtube-player has been developed by Dominic Tarr. He kindly released the NPM namespace of youtube-player for this project. The original code can be found at