Demo THEOplayer
Implementing continuous play with JS cookies and THEOplayer API
This page demonstrates how you can manipulate the default THEOplayer UI, using CSS, JavaScript and THEOplayer API.
How does it work?
Continuous play enables the possibility to restore a viewer's playhead position from a previous session. For example, a viewer is watching a video and stops viewing it 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.theoplayer.com/getting-started/01-sdks/01-web/00-getting-started.md
// 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 "";
}