Youtube Iframe API
Easily create and interact with embedded YouTube videos
view on
github

About

This library is a reworking of YouTube's default embedding iframe API. It contains a few extra features and has readable and modifiable source code. It can be directly integrated into an existing script or loaded as a stand-alone script.

It can also be used to learn how the basic postMessage system communicates between the main window and the embedded iframe.

Feature Comparison

  • Extra events with extra information
    YouTube's API contains 6 usable events. This custom API contains all of these events plus several extra state changing events for things such as volume, load progress, and playlist entry changing. Additionally, these events expose the previous value before the change.
  • No onYouTubeIframeAPIReady event required
    YouTube's API requires a function called onYouTubeIframeAPIReady to exist somewhere in a <script> tag on the page. This makes it very difficult (or impossible) to use their API inside of a userscript, because the event (and subsequently the YT object) will exist on the main window object and not inside the userscript.
  • No required state polling
    YouTube's API provides a limited amount of events for checking state updates. As such, things like load progress or current time would require a poll loop. With more events available for use, a poll loop is no longer required for state update.
  • No repeating listening message
    YouTube's API repeatedly postMessage's a listening event to the iframe every 250ms. Testing seems to indicate that this message is needed only once, so this custom script only sends it once. There could be a reason for this on some untested edge cases or mobile platforms, but none have been found yet.
  • Less http requests for scripts
    Including YouTube's iframe_api script effectively loads 2 scripts instead of one. The iframe_api is just a loader script and inserts another <script> node for the actual API. The second script is automatically async as well with no options to control this.
  • Potentially more prone to breaking
    As this script is a third-party library, if YouTube drastically changes the way their API functions, this script has to be updated too. Looking at YouTube's API update history, this does not seem to be likely to happen though.

Download

Documentation

This documentation is fairly minimal in an effort to not over-rewrite or copy YouTube's original documentation. For most of the functions listed on this page, their parallels can be found in the original documentation, which may contain some extra info about arguments and such.

The extended descriptions are minimized by default for ease of locating functions by name. Click the +/ or the function name to expand/shrink the description. (expand all | shrink all)

References

Youtube Module

  • Youtube. : Array
    An array containing the current version of the API. For example, [1, 0] represents version 1.0.
  • Youtube. : boolean
    A boolean telling if the module can be supported. This basically checks if postMessage is available.

Player Class

  • new Youtube.(settings...) : instance
    Create a new instance. This will create and set up all state variables, events, and the iframe, but will not insert it into the DOM. This is left up to the user.
    settings : object

    An object describing the settings to create the player with. The format of the object should be as follows:

    { video_id: /* string id of the video */, https: /* true or false; setting to false uses http: embedding (may not work) */ params: { /* key:value pairs of player parameters */ }, on: { /* key:value pairs of event_name:callbacks */ }, }

    return : instance
    A new instance of the Player class
  • Player.()
    Destroys the player, removing any event listeners applied to it or any DOM nodes related to it. Also removes the iframe from the DOM.
  • Player.() : DOM node
    Returns the iframe node that contains the player.
    return : DOM node
    The iframe node
  • Player.() : DOM node
    Returns if any ready events have already been fired.
    return : DOM node
    true if the player can properly accept commands, false otherwise
  • Player.=-1,
    Player.=0,
    Player.=1,
    Player.=2,
    Player.=3,
    Player.=5
    Constants representing the state of a player. Their names are self explanatory.

Player Queueing

Note that for the following three functions, only the first argument is required. The remaining arguments are optional, and a default is used if they are set to null or undefined.

  • Player.(video_id, autoplay, quality, start_time, end_time...)
    Loads a new video into the player given a video id.
    video_id : string
    The id of the video to load
    autoplay : boolean
    If true, the video will (under most circumstances) autoplay
    quality : string
    The desired quality level of the video to play
    start_time : number
    The time (in seconds) to start playing the video at
    end_time : number
    The time (in seconds) to stop playing the video at
  • Player.(video_url, autoplay, quality, start_time, end_time...)
    Loads a new video into the player given a video url.
    video_url : string
    The url of the video to load
    autoplay : boolean
    If true, the video will (under most circumstances) autoplay
    quality : string
    The desired quality level of the video to play
    start_time : number
    The time (in seconds) to start playing the video at
    end_time : number
    The time (in seconds) to stop playing the video at
  • Player.(playlist, type, index, autoplay, quality, start_time...)
    Loads a playlist into the player. The playlist can be a custom playlist, a pre-existing playlist, a search results playlist, or a user uploads playlist.
    playlist : string | Array
    If this argument is an array, then it should be an array of video ids in the order they should be played. Otherwise, it depends on the value of playlist_type:
    • "playlist"
      The id of a YouTube playlist
    • "search"
      The search term for the videos
    • "user_uploads"
      The name of the user
    type : string
    The type of playlist to load. This can be either "playlist", "search", or "user_uploads". If unspecified, the default is "playlist". If playlist is an array, this argument is ignored.
    index : number
    The first video in the playlist to play as a 0-indexed number
    autoplay : boolean
    If true, the playlist will (under most circumstances) autoplay
    quality : string
    The desired quality level of the video to play
    start_time : number
    The time (in seconds) to start playing the first video at

Video/Playlist Playback

  • Player.()
    Plays the video; the state will be set to PLAYING.
  • Player.()
    Pauses the video; the state will be set to PAUSED.
  • Player.()
    Stops the video. Should only be used when the player is completely done and won't be used again.
    The state will be set to one of the following: ENDED, PAUSED, CUED, or UNSTARTED.
  • Player.()
    Clears any video remnant once the video is stopped.
  • Player.()
    Mutes the video.
  • Player.()
    Unmutes the video.
  • Player.(timecode, allow_seek_ahead...)
    Seeks to a position in the video.
    timecode : number
    The timecode (in seconds) to seek to
    allow_seek_ahead : boolean
    If true, the video is allowed to skip out of the presently buffered region.
    When seeking, this should be set to false and called again with true when seeking is done (i.e. on a mouseup event.)
  • Player.()
    Skips to the next video in a playlist.
  • Player.()
    Skips to the previous video in a playlist.
  • Player.(index...)
    Skips to a specified video in a playlist.
    index : number
    The 0-indexed video to skip to

Player State

  • Player.() : boolean
    Returns if the video is muted or not.
    return : boolean
    Returns true if muted, false otherwise
  • Player.() : number
    Get the volume.
    return : number
    Returns a number in the range 0 to 100 corresponding to a percent
  • Player.(volume...)
    Set the volume.
    volume : number
    A number in the range 0 to 100 corresponding to the percent of desired volume
  • Player.() : number
    Get the rate of playback.
    return : number
    Returns the rate at which the video is playing. Example values include 0.25, 0.5, 1.0, 1.5, and 2.0.
  • Player.() : Array
    Get the available playback rates.
    return : Array
    Returns a list of rates at which the video can be played at
  • Player.(rate...)
    Set the rate of playback.
    rate : number
    The speed at which to play the video. Available values can be discovered by calling get_playback_rates_available.
  • Player.() : string
    Get the playback quality.
    return : string
    Returns the quality level of the video
  • Player.() : Array
    Get the available playback qualities.
    return : Array
    Returns a list of qualities the video supports
  • Player.(quality...)
    Set the playback quality.
    quality : string
    Set the desired quality of the video. Available values can be discovered by calling get_playback_qualities_available.
  • Player.(loop...)
    Set if the playlist should loop on completion.
    loop : string
    true if playlist should loop, false otherwise.
  • Player.(shuffle...)
    Set if the playlist should shuffle.
    shuffle : string
    true if playlist should shuffle, false otherwise.
  • Player.() : number
    Get the percent of the video loaded.
    return : number
    The percentage of the video loaded. 0.0 is nothing loaded, 1.0 is completely loaded.
  • Player.() : integer
    Get the current state of the video player.
    return : integer
    The constant representing the player's current state. The value should be one of the STATE_CONSTANTS.
  • Player.() : number
    Get the current time the video is at.
    return : number
    The current time in seconds
  • Player.() : number
    Get total length of the video.
    return : number
    The total length in seconds
  • Player.() : object
    Returns info about the currently playing video, such as video id, author, and title.
    return : object
    An object containing info about the video
  • Player.() : null | Array
    Get the current playlist.
    return : null | Array
    If no playlist is being used, null is returned. Otherwise, it's an array of video ids. If set_shuffle was called, this return value reflects the shuffled playlist.
  • Player.() : integer
    Get the current index into the playlist.
    return : integer
    If no playlist is being used, -1 is returned. Otherwise, it's a 0-indexed number into the playlist.

Extended API

The extended API covers other settings YouTube provides control over that may or may not be available on every video.

Note that YouTube's documentation on their similar getOption, getOptions, and setOption functions is dated. Explore the get_api return value to discover which options are available.

  • Player.() : object
    Returns the complete available extended API. The return value should be read-only, as modifying it directly does nothing.
    return : object
    An object of the form:
    { module1: { option1: /* some type of value */, option2: /* some type of value */, ... }, module2: { ... }, ... }
  • Player.(module, option, value...)
    Modifies extra API values. An "api_change" event should trigger after a successful update.
    module : string
    The name of the module
    option : string
    The option of the module
    value : any
    The value to set the option to

Player Events

Unless otherwise specified, the event data of all events are called with an event_data argument of the form:

{ current: { /* key:value pairs of the new values */ }, previous: { /* key:value pairs of the old values */ }, }

  • Player.(event_name, callback...) : boolean
    Adds a new event listener to the player instance.
    event_name : string
    The name of the event to listen for
    callback : function

    A function to be called when the event is triggered. The this object of the call will be the player instance, and the first argument contains any event-specific data.

    callback.call(player_instance, event_data)

    return : boolean
    true if the event exists and the callback was added, false otherwise
  • Player.(event_name, callback...) : boolean
    Removes an existing event listener from the player instance.
    event_name : string
    The name of the event to remove the listener from
    callback : function
    The event listener to remove
    return : boolean
    true if the callback was successfully removed, false otherwise

  • event.

    This event will be called as soon as it can be. This means, if the iframe triggers it's ready event, all callbacks will trigger at this point. If a callback is added after the iframe event triggers, it will fire inside the on call.

    The event_data is of the form:
    { immediate: /* true or false */ }
    The immediate entry will be true if it was called during the on call, and false otherwise.

  • event.
    This event fires when a state change occurs.
  • event.
    This event fires when a volume change or muted change occurs.
  • event.
    This event fires when the video's current time changes.
  • event.
    This event fires when the video's duration changes.
    This usually happens when the precision of the duration changes (i.e. integer number to a floating point.)
  • event.
    This event fires when the loaded fraction changes.
  • event.
    This event fires when the playback quality changes.
  • event.
    This event fires when the playback rate changes.
  • event.
    This event fires when the list of available playback qualities changes.
  • event.
    This event fires when the list of available playback rates changes.
  • event.
    This event fires when the available video data changes.
  • event.
    This event fires when the playlist changes.
  • event.
    This event fires when the current playlist index changes.
  • event.
    This event fires when an API change occurs.

  • event.

    This event fires when a state change occurs. It uses the native event provided by YouTube's API.

    The event_data is of the form:
    { value: /* new state */ }

  • event.

    This event fires when a playback quality change occurs. It uses the native event provided by YouTube's API.

    The event_data is of the form:
    { value: /* new quality */ }

  • event.

    This event fires when a playback rate change occurs. It uses the native event provided by YouTube's API.

    The event_data is of the form:
    { value: /* new rate */ }

  • event.

    This event fires when an API change occurs. It uses the native event provided by YouTube's API.

    The event_data is of the form:
    { value: null }

  • event.

    This event fires when an error occurs. It uses the native event provided by YouTube's API.

    The event_data is of the form:
    { value: /* error info */ }

Demo

The demo requires Javascript enabled to use. The demo is loading... To begin the demo, click here.
Actions Playback Loading Playlist
State Extended API Event Log