Last active
June 22, 2020 15:56
-
-
Save brgaulin/abf6b497eb8e6e3641cedb8977dba939 to your computer and use it in GitHub Desktop.
Video.js Window Postmessage
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import videojs from 'video.js'; | |
const throttle = (func, limit) => { | |
let inThrottle | |
return function () { | |
const args = arguments | |
const context = this | |
if (!inThrottle) { | |
func.apply(context, args) | |
inThrottle = true | |
setTimeout(() => inThrottle = false, limit) | |
} | |
} | |
} | |
const sendMessage = (payload) => { | |
window.postMessage(payload, '*'); | |
console.debug("VideoPlayer: ", payload); | |
} | |
const player = videojs('my-video', { | |
controls: true, | |
fill: true | |
}); | |
player.on('loadeddata', function () { | |
sendMessage({ | |
type: 'loaded', | |
path: '', | |
totalDuration: +this.duration().toFixed(2) | |
}); | |
}); | |
const timeUpdate = function() { | |
if(this.played().length === 0) { | |
return; | |
} | |
let watchedRanges = this.played(); | |
let watchedSeconds = 0; | |
for (let i = 0; i < watchedRanges.length; i++) { | |
watchedSeconds += watchedRanges.end(i) - watchedRanges.start(i); | |
} | |
sendMessage({ | |
type: 'timeupdate', | |
totalDuration: +this.duration().toFixed(2), | |
currentTime: +this.currentTime().toFixed(2), | |
currentTimePercent: +(this.currentTime() / this.duration() * 100).toFixed(2), | |
secondsWatched: +watchedSeconds.toFixed(2), | |
watchedPercent: +(watchedSeconds / this.duration() * 100).toFixed(2) | |
}); | |
} | |
player.on('timeupdate', throttle(timeUpdate, 15000)); // Only trigger this function once every 15s | |
player.on('play', function () { | |
sendMessage({ type: 'play' }); | |
}); | |
player.on('pause', function () { | |
sendMessage({ type: 'pause' }); | |
timeUpdate.bind(player)(); | |
}); | |
player.on('ended', function () { | |
sendMessage({ type: 'ended' }); | |
timeUpdate.bind(player)(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment