Demo THEOplayer

Implementing continuous play with js cookies THEOplayer

This page demonstrates how you can manipulate the default THEOplayer UI, using CSS, JavaScript and THEOplayer API.

logo-01

How it works?

Continuous play enables the possible to restore a viewer's playhead position from a previous session. For example, a viewer is watching a video and stops viewing after three minutes. The next time the viewer visits the page, the video will start playing again from the third minute.

In this demo, we use the browser's cookie storage as the database storing the last playhead position. These cookies can be set and fetched with JavaScript. Of course, a (remote) database is a possible alternative to store this type of data.

Properties used from the Player API:

  • player.currentTime: current playhead position.
  • player.src: current video source.

Events used from the Player API:

  • timeupdate: thrown periodically when currentTime changes.
 

JavaScript

// information on setting up THEOplayer and the player object can be found at https://docs.portal.theoplayer.com/docs/docs/getting-started/web/web

// video data
var videoUrl = "http://cdn.theoplayer.com/video/big_buck_bunny/big_buck_bunny_metadata.m3u8",
    videoId = "V1";
   
// fetch currentTime from (cookie) storage
var previousPlayheadPosition = getCookie('playheadPosition'+videoId);

 // update player with bookmark config
    player.src = videoUrl;
    if (previousPlayheadPosition) {
        player.addEventListener('play', setpreviousPlayheadPosition);
    }
  
  function setpreviousPlayheadPosition(){
    player.currentTime = previousPlayheadPosition;
    player.removeEventListener('play', setpreviousPlayheadPosition)
  }

// frequently store playhead position in cache storage
player.addEventListener('timeupdate', function() {
   setCookie('playheadPosition'+videoId, player.currentTime); 
});
    
// update a cookie
function setCookie(cname, cvalue) {
    var d = new Date();
    d.setTime(d.getTime() + (7 * 24 * 60 * 60 * 1000)); // store 7 days
    var expires = "expires="+d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

// fetch a cookie
function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

Still wasting time debugging video playback problems?

Welcome to cutting-edge video, delivered efficiently and on any platform. We think you're going to like it.