JavaScript API

Global API access

Use the flowplayer function to get a global handle on the API. Here we attach two custom events to the API of all players which will be installed on the page:

flowplayer(function (api, root) {

  api.on("load", function () {

    // do something when a new video is about to be loaded

  }).on("ready", function () {

    // do something when a video is loaded and ready to play

  });

});

[View standalone demo]({{ config.flowplayer7.standalonedemos }}/api/access)

This anonymous callback function is provided by the Flowplayer library and is called every time a Flowplayer instance is created. Think of it as a "mini-plugin".

You use it to customize the default behaviour of all players on your page in a similar manner as you set global configuration options, and thus it should be called right after the flowplayer script is included in the HEAD section of the page and before the page is loaded - before the DOM (Document Object Model) is ready.

The API is provided by the first argument and it looks like this in the browser console:

API

Console screenshot

Via the second argument - called root above - you can access the root or container element of the player.

The global flowplayer function is the only place to catch the initial load event in non splash setups.

Selective API access

Once the players are installed initialized you can access specific player instances like this:

// get the first player
var api = flowplayer();

// same thing with jQuery
api = $(".flowplayer:first").data("flowplayer");

// and the second player
api = flowplayer(1);

// .. with jQuery
api = $(".flowplayer:eq(1)").data("flowplayer");

// use any jQuery selector
api = $(".mycustom.flowplayer").data("flowplayer");

// return the API in given jQuery object
api = flowplayer($(".myplayer"));

// or DOM object
var elem = document.getElementById("myplayer");
api = flowplayer(elem);

The installation method determines when you have access to selected APIs:

Instant API access

The pure JavaScript installation allows instant API access to the specific instance:

var api = flowplayer("#player", {
  // player configuration goes here
});

Contrary to the other selective API access methods the API is accessible in a 1-step operation.

Properties

During its life cycle the player is in varying states which are reflected in the the properties of the API. Here is a complete list of the API properties:

    • property
    • description
    • conf object
    • the initial configuration object
    • currentSpeed integer
    • the current playback speed level:
      - 1 = normal speed
      less than 1 = slow motion
      greater than 1 = fast forward Default: 1
    • disabled boolean
    • true while the player is disabled Default: false
    • dvr boolean
    • true while the current video is a live DVR stream Default: false
    • engine object
    • the chosen video engine, the name of the engine can be retrieved as engine.engineName
    • error boolean
    • true once an error has occured Default: undefined
    • finished boolean
    • true while the player is stopped at the end of the video Default: false
    • forcedSplash boolean
    • whether a splash setup was enforced for this player, true on mobile devices Default: false
    • isFullscreen boolean
    • true while the player is in fullscreen mode Default: false
    • live boolean
    • true while the current video is a livestream, also live DVR Default: false
    • loading boolean
    • true while the player is being loaded Default: false
    • muted boolean
    • true while the player is muted Default: false
    • paused boolean
    • true while the player is paused Default: false
    • playing boolean
    • true while the player is playing Default: false
    • poster boolean
    • true while the player is in [poster state](../setup#poster Default: false
    • ready boolean
    • true once the player API is ready and completely loaded Default: false
    • rtl boolean
    • true if the player has a right-to-left layout Default: false
    • seeking boolean
    • true while the player is seeking Default: false
    • splash boolean
    • true while the player is in splash state Default: false
    • volumeLevel integer
    • the current volume level between 0 and 1 Default: 0.8

Depending on the state of the player at the moment when you grab the API or call one of its methods, the full depth of its properties might be not be available.

For example: Before the player is ready video metadata such as its duration has not been processed and is therefore undefined. Similarly you cannot obtain a sensible value for the current playback position at all times. A safe way to retrieve that position would be:

var api = flowplayer(), currentPos;

// get the current position, default to 0
currentPos = api.ready ? api.video.time : 0;

API properties should be considered as read only. Use API methods to change the state of the player and its properties. Setting properties is only needed in advanced cases and situations which often should be avoided in the first place, like in [this demo]({{ config.flowplayer7.demos }}/scripting/recover.html) which recovers from an invalid video location.

When skinning is involved you can often achieve your scripting goals with pure CSS programming by defining rules for the state classes instead of querying JavaScript API properties.

Extension and plugin properties

The following properties are provided by player extensions and plugins. Follow the link in the third column for further details:

Video object

The video property is a reference to the currently playing video. Here is an example:

{
  // the length of the available buffer in seconds - not available over RTMP
  buffer: 15.43,

  // flag indicating whether the buffer is fully loaded
  buffered: false,

  // length of video in seconds
  duration: 18.85,

  // width of video file in pixels
  width: 640,

  // height of video in pixels
  height: 280,

  // whether the [server](index.html#server-side) supports random jumping on timeline
  seekable: true,

  // path to currently playing video as given on setup
  src: 'http://mydomain.com/video1.m3u8',

  // current playback position in seconds
  time: 5.27681660899654,

  // video format (media type)
  type: 'application/x-mpegurl',

  // array of video formats
  sources: [
    { type: 'application/x-mpegurl', src: '//mydomain.com/video1.m3u8', suffix: 'm3u8' },
    { type: 'video/mp4',  src: '//mydomain.com/video1.mp4',  suffix: 'mp4'  }
  ],

  // video filename suffix
  suffix: 'm3u8',

  // absolute URL of the video
  url: 'http://mydomain.com/video1.m3u8',

  // [HLS quality selection](setup.html#hls-quality-selection)
  qualities: [-1, 0, 1, 2, 3, 4],
  quality: -1,

  // the clip title (if configured)
  title: 'My video'
}

Check out [this demo]({{ config.flowplayer7.demos }}/api/videoinspect.html) which prints the entire video object to the page for inspection.

Extension and plugin video properties

The following video object properties are provided by player extensions and plugins. Follow the link in the third column for further details:

Methods

    • method
    • description
    • disable([flag])
    • disable() without argument toggles between disabled and normal API state. disable(true) disables and disable(false) enables the API.
      While the API is disabled loading, pausing, resuming and seeking is not possible. The progress bar is greyed out (color configurable via CSS).
    • fullscreen()
    • Toggles between native fullscreen mode and initial screen size. When native fullscreen support is not present the player expands to the full size of the browser window.
      Note: Many browsers allow this method to work only from events which are triggered by user interaction, like "click", and not for example from player events like "ready" which happen at moments undetermined by the user.
    • load([video], [callback])
    • Loads the player with the specified video. See the section on the load method.
    • message(text)
    • Normally used to display a fatal error message, message() may come in handy to notify the user with a custom alert as in [this demo]({{ config.flowplayer7.demos }}/scripting/recover.html).
    • mute([flag])
    • Normally used to display a fatal error message, message() may come in handy to notify the user with a custom alert as in [this demo]({{ config.flowplayer7.demos }}/scripting/recover.html).
    • pause([callback])
    • Pauses playback.
    • quality(quality)
    • Switches playback to HLS quality index given in argument. The index is zero-based for fixed qualities in the configured hlsQualities array, -1 for adaptive.
      For VOD quality selection see the method of the same name provided by the VOD quality selector plugin.
    • resume()
    • Resumes playback.
    • seek(time, [callback])
    • Seeks to the given position in seconds. For example: 13.5.
      The callback is executed once after the seek.
    • seek(flag, [callback])
    • seek(true) seeks 10% forward and seek(false) seeks 10% backward. Same as pressing or on the keyboard.
      The callback is executed once after the seek.
    • seekTo(position, [callback])
    • seekTo(1) jumps to 10% on the timeline, seekTo(2) goes to 20% and so on.
      The callback is executed once after the seek.
    • seekTo()
    • Seeks to last seek position. Same as pressing . on thekeyboard.
    • shutdown()
    • Destroys the player instance. Call this method before you remove the container element from the page, or before you remove the player from it. This way all Flowplayer event handles are cleaned up as well.
      Caveat: Like unload() which is called internally by it, this method requires a splash setup for perfect cleanup. Also prefer unload() whenever possible to avoid unnecessary DOM manipulations and prevent race conditions with immediately ensuing actions by wrapping them in the callback of the shutdown event.
    • speed(rate, [callback])
    • Sets the speed level to the given rate.
      1 = normal speed
      less than 1 = slow motion
      greater than 1 = fast forward
      The callback is executed once after the speed has changed.
    • speed(flag, [callback])
    • speed(flag, [callback]) | Changes the speed based on the speed configuration variable.
      speed(false) switches backward on the speed array.
      speed(true) switches forward.
      The callback is executed once after the speed has changed. |
    • stop()
    • Pauses playback and seeks to the beginning of the video.
      In aposter setup the player goes back into poster state.
    • toggle()
    • Pauses playback and seeks to the beginning of the video.
      In aposter setup the player goes back into poster state.
    • trigger(type, args)
    • Triggers a player event. 2 mandatory arguments:
      1. the event type
      2. an array of arguments with at least one member; the first item must be the API instance, the second must be provided if the event provides a third argument.
    • unload()
    • In a splash setup unloads the player back to the splash state.
      In non-splash setups the player is not unloaded but goes back to its initial state, the poster or first video frame is shown.
    • volume(level)
    • Set the volume level to a decimal value between 0.0 (no volume) and 1.0 (full volume). The volume level is remembered between page loads.

All methods return the API object, with the exception of shutdown(). This allows method chaining:

// re-enable the api for the 2nd player on the page and resume
flowplayer(1).disable(false).resume();

See also the methods for event handling.

Extension methods

The following methods are provided by player extensions. Follow the link in the second column for further details:

Load method

Load player

Without argument the load() method initializes player and video from the splash state on demand:

api.load();

A VIDEO or OBJECT tag is created depending on browser or engine preference.

Load video

load() also accepts a clip object as argument in the same way a pure JavaScript installation does as value to the clip option. The video represented by this clip object is then loaded into an existing player instance:

api.load({
  sources: [
    { type: "application/x-mepgurl",
      src:  "//mydomain.com/video2.m3u8" },
    { type: "video/mp4",
      src:  "//mydomain.com/video2.mp4"  }
  ]
});

The following shorthands are available for the clip object argument:

  • Array of sources
api.load([
  { mpegurl: "//mydomain.com/video2.m3u8" },
  {     mp4: "//mydomain.com/video2.mp4"  }
]);

This shorthand does not accept further clip or source options.

  • URL as string
api.load("//mydomain.com/my/another/video2.mp4");

This shorthand does not accept further clip or source options. And it expects the same source types to be present as configured for the player instance referenced by the API. Additionally the sources must be available via HTTP and obey the same file naming scheme: they can only differ by their filename suffix.

The above shorthand could be applied successfully to the following player for example:

<div class="flowplayer">
   <video>
      <source type="application/x-mpegurl" src="//mydomain.com/video1.m3u8">
      <source type="video/mp4" src="//mydomain.com/video1.mp4">
   </video>
</div>

If in doubt go for the full clip object syntax instead of using a shorthand. This will make your code more self explanatory, transparent and easier to maintain in the long term.

  • Callback
api.load({
  sources: [
    { type: "application/x-mepgurl",
      src:  "//mydomain.com/video2.m3u8" },
    { type: "video/mp4",
      src:  "//mydomain.com/video2.mp4"  }
  ]
}, function (e, api, video) {;
  console.log(video.duration);
});

The callback function will be invoked when the player is ready and the new video is about to start.

Events

The attaching methods can be used to execute custom JavaScript when a specified event happens in the player. For example:

api.on("pause", function(e, api) {

   // do your thing when the player is paused

});

The first argument is the event name or a space separated string of several event names, and the second is a callback function which is fed with 2 or 3 arguments:

  1. The event object; if the event was attached via jQuery, the jQuery event object. Provides fine-grained event control via its properties.
  2. Provides a handle on the player API.
  3. Optional, depends on the event.

The event properties, like target, type etc., can be inspected in the browser console:

api.on("mute", function (e) {
    console.log(e);
});

Here is a complete list of player events:

    • event
    • fires
    • beforeresume
    • Before playback is resumed.
    • beforeseek
    • Before seeking starts at the origin position. The 3rd argument gives access to the seek target position. By callingevent.preventDefault() (where event is the callback's 1st argument) the seek can be stopped.
    • buffer
    • When the browser downloads video. The 3rd argument provides the time position up to which the video is buffered, the equivalent of the value of the buffer property of thevideo object at this moment.
    • disable
    • When the player toggles between disabled and normal state. In disabled mode the UI elements cannot be used.
    • error
    • When an error occurred. The 3rd argument provides an object featuring the code and message properties. See theerror table below.
    • finish
    • When playback has finished.
    • flashdisabled
    • When the Flash engine fails, or when it must be enabled by explicit user interaction, a message that Flash is disabled is shown - typical scenario:small Flash object in recent Chrome. See[this demo]({{ config.flowplayer7.demos }}/api/live-check.html#javascript-setup) for how to hide the message once in a clear cut error scenario.
    • fullscreen
    • When the player goes to fullscreen mode.
    • fullscreen-exit
    • When player exits fullscreen mode.
    • load
    • First event in the lifecycle of a clip, before the configured clip or a new video starts playing. Offers an opportunity to alter the video properties. The 3rd argument provides thevideo object featuring basic data like src, but not yet the video metadata from the server (such as duration). Returning false will prevent the video from loading.
      Note: In nonsplash setups the initial load event is only available via theglobal flowplayer function.
    • mute
    • When the player's mute state is toggled.
    • pause
    • When playback is paused.
    • progress
    • When the playhead moves forward. Happens approximately every 250 milliseconds during playback. The 3rd argument provides the current playback position, i.e. the current value of the time property of thevideo object.
    • quality
    • When a hlsQuality is manually selected. The 3rd argument provides index of the selected HLS level.
      For VOD quality selection see the event of the same name provided by theVOD quality selector plugin.
    • ready
    • When the video is fully loaded and video metadata (such as duration) becomes available from thevideo object which is provided by the 3rd argument.
    • resume
    • When playback is resumed.
    • seek
    • When seeking is completed at the target position. The 3rd argument gives access to the target position.
    • shutdown
    • When the player and API instance is destroyed, after the shutdown()method has been invoked. Last event in a player's life cycle.
    • speed
    • When the playback speed is changed. The new level is provided by the 3rd argument.
    • stop
    • When playback is stopped by the stop()method.
    • volume
    • When the volume level is changed. The new level is provided by the 3rd argument.

You will often find that Flowplayer\'s CSS programming capabilities provide a more elegant way to customize the player\'s look and feel dynamically according to its state.

Error codes

Error codes and error messages returned by the third argument of the error event are mapped the following way:

    • error
    • error message
    • 1
    • Video loading aborted
    • 2
    • Network error
    • 3
    • Video not properly encoded
    • 4
    • Video file not found
    • 5
    • Unsupported video
    • 6
    • Skin not found
    • 7
    • SWF file not found
    • 8
    • Subtitles not found
    • 9
    • Invalid RTMP URL
    • 10
    • Unsupported video format. Try installing Adobe Flash

Errors 1 through 4 are HTML5 video exceptions, errors 5 through 10 are Flowplayer exceptions.

Extension events

The cuepoint event is provided by 2 player extensions. Follow the link in the second column for further details:

Attaching events

The following methods attach (or detach) events:

    • method
    • description
    • bind()
    • Alias for the on() method.
    • off()
    • Removes the event handler(s) specified in the 1st argument. No callback, unless the event was attached to the container viajQuery.
      Similar to thejQuery method of the same name.
    • on()
    • Attaches the callback in the 2nd argument to the events specified in the 1st argument.
      Similar to thejQuery method of the same name.
    • one()
    • One time event handle. The callback in the 2nd argument is fired once for (each of) the event(s) specified in the 1st argument.
      Similar to thejQuery method of the same name.
    • unbind()
    • Alias for the off() method.

Events can be attached either to the API, or, with the help of jQuery, to the container element.

Multiple events can be attached in one call by passing their names in a space separated string in the first argument:

api.on("fullscreen fullscreen-exit", function (e, api) {
    if (/exit/.test(e.type)) {
       // do something after leaving fullscreen
    } else {
       // do something after going fullscreen
    }
});

API event binding

Normally events are simply attached to the API, like in the example above.

Events attached to the API return the API object.

jQuery event binding

You can also bind your events directly to the jQuery object referencing the container element. For example:

$(".flowplayer:first").on("pause", function(e, api) {
  // do something on pause
});

This makes for seamless integration of the Flowplayer API into custom jQuery plugins.

Events attached via jQuery return the jQuery object of the container element.

As this is a jQuery event, the this keyword refers to the root or container element of the player within the callback. It corresponds to the currentTarget property of the first argument.

Name space

All Flowplayer events can be confined to a specific name space when you attach them:

api.on("pause.mypause", function (e, api) {
  // do something on pause
});

Flowplayer event name spaces work as in jQuery, but do not require jQuery to be loaded. They come in handy for instance if you want to turn off a specific callback:

// turns off pause.mypause, but not the entire pause callback
api.off("pause.mypause");

Attaching to JavaScript installation

Events can immediately be attached to the API of a specific JavaScript installation:

flowplayer("#player", {
  // player configuration goes here
}).on("pause", function (e, api) {
  // do something on pause with this player
});

Attaching to manual installation

Events can immediately be attached to the container jQuery object of a specific manual installation:

$(".player").flowplayer({
  // player configuration goes here
}).on("pause", function (e, api) {
  // do something on pause with these players
});

This way of attaching events to the container element is strongly discouraged! In splash setups it will catch the load event only because the VIDEO tag is replaced on load. As splash setups are enforced on mobile devices, this is bound to lead to unexpected behaviour. Use the pure JavaScript installation to chain events directly to an install script or access the API selectively in a second step.

Event chaining

All Flowplayer events return the API, or, if attached via jQuery the jQuery object of the container element. Therefore event bindings can be chained:

api.on("pause", function (e, api) {
  // do something on pause
}).on("resume", function (e, api) {
  // do something on resume
});

Event prevention

In some situations it is desireable to prevent player events from happening or to limit their scope, and optionally take a different action. To achieve this the Flowplayer API offers two methods which can be chained to the event variable provided by first arg

    • method
    • effect
    • e.preventDefault()
    • The default action of this event will not be triggered.
      Note: In rare cases one may have to use brute force and simply return false from within the event, but calling this method should be preferred.
      Similar to the jQuery method of the same name.
    • e.stopPropagation()
    • Other handlers of this event will not be notified.
      Similar to the jQuery method of the same name.

[This demo]({{ config.flowplayer7.demos }}/lookandfeel/noseek.html) gives an example of both methods in action to show how seeking can be disabled.

Engines

Flowplayer ships with two engines named html5 and flash. They share a common engine interface which is implemented as follows:

var engineImpl = function (player, root) {

    var engine = {
        engineName: engineImpl.engineName,

        pick: function (sources) {
            // engine specific picking mechanism

        },

        load: function (video) {
            // how this engine loads the video

        },

        resume: function () {
            // how this engine resumes playback

        },

        /* etc. */

    };

    return engine;
};

engineImpl.engineName = "myengine";
engineImpl.canPlay = function (type, conf) {
    // return boolean whether this engine can play media of type type
    // in the player configuration conf

};
// prepend the engine to the existing engines
flowplayer.engines.unshift(engineImpl);

Look for the implementation details in Github.

window.flowplayer

The flowplayer function is used for accessing the player, making extensions and engines. It also provides the following properties:

// version number
var version = flowplayer.version;

// default configuration for all players (v5.1)
flowplayer.defaults;

// global configuration to override defaults
flowplayer.conf = { };

// list of engines which are supported by the browser
flowplayer.engines

flowplayer.set

The flowplayer.set method allows to extend the existing global configuration without discarding other existing top-level settings, thereby offering more flexibility compared to specifying the flowplayer.conf object directly.

A typical scenario where this comes in handy: All pages on a site load a default script which contains Flowplayer configuration settings, but you want to override selected settings without discarding others:

flowplayer.set({
    // all videos on this page have a 4:3 aspect ratio
    ratio: 3/4,
    // all players on this page should use a splash setup
    splash: true,
    // common hlsjs configuration to all players
    hlsjs: {
        startLevel: -1
    }
});

Like anything relating to global configuration, flowplayer.set should be used only in the HEAD section of your page, before the DOM is ready.

If the specified property is itself an Object, its nested properties are still overridden, also by omission. In the example above one would have to repeat any previous hlsjs settings if still applicable. Only previous top-level values are merged.

flowplayer.support

flowplayer.support is a collection of properties that represent the presence of different browser features. If for example HTML5 video is supported then flowplayer.support.videois true. Here are the supported properties:

  • android - {{ since('7.0.4') }} returns information about the current Android device, false otherwise
  • autoplay - {{ since('7.0.4') }} whether autoplay is supported; synonymous to firstframe
  • animation - CSS3 animation support
  • browser - returns information about current browser and version
  • cachedVideoTag - whether video tag can be cached
  • dataload - whether any video data can be loaded before hitting play
  • flashVideo - flash video support
  • flex - whether flexible boxes are supported
  • firstframe - support for display of first video frame on load; synonymous to autoplay
  • fullscreen - native HTML5 fullscreen support
  • fullscreen_keyboard - keyboard support in fullscreen mode
  • hlsDuration - whether duration of HLS stream is natively recognized
  • iOS - returns information about current iOS device
  • inlineBlock - CSS inline-block support
  • inlineVideo - support for playing video inline
  • mutedAutoplay - {{ since('7.1.0') }} whether the (mobile) browser supports muted autoplay
  • seekable - support for seeking when video is ready
  • subtitles - native subtitle support
  • svg - whether scalable vector graphics for the skin are supported
  • touch - touch interface support
  • video - HTML5 video support
  • volume - volume support via JavaScript API
  • zeropreload - whether preload="none" completely disables preloading

Refer to [this page]({{ config.flowplayer7.demos }}/videotest/support.html) for the results with your current browser.

Migration from Version 5

The second argument provided by the anonymous callback of the global API setup function is not a jQuery object anymore but a reference to the container element itself. If jQuery is loaded, you can still access the container element the jQuery way like this:

flowplayer(function (api, root) {
  root = $(root);
  // ... code referring to root as jQuery object
});

[recover]: {{ config.flowplayer7.demos }}//scripting/recover.html

[MINITOC]

Results