<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<video id="video" width="320" height="240" controls>
<source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
</video>
<script type="application/javascript">
const videoPlayer = document.getElementById('video');
let intervalHandle = null;
let videoId = null;
const saveFreq = 1 * 1000;// x*1000 = n seconds.
if (videoPlayer) {
let videoSource = videoPlayer.querySelector('source');
if (videoSource) {
videoId = videoSource.src;
}
}
console.log('working on video src: ', videoId);
videoPlayer.addEventListener('play', function(event) {
intervalHandle = setInterval(function() {
if (videoId === '' || videoId === null) {
videoId = videoPlayer.currentSrc;
}
savePosition(videoId, videoPlayer.currentTime);
}, saveFreq);
});
video.addEventListener('pause', (event) => {
clearInterval(intervalHandle);
});
const getPosition = function(videoId) {
console.log('getting last played of video src: ', videoId);
const defaultPosition = {
'videoId': videoId,
'position': 0
};
try {
let storageResult = localStorage.getItem('video_player_position');
if (storageResult) {
return JSON.parse(storageResult);
} else {
return defaultPosition;
}
} catch (error) {
}
return defaultPosition;
}
const savePosition = (videoId, position) => {
console.log('saving position. videoId: ' + videoId + ', position: ' + position);
try {
localStorage.setItem(
'video_player_position',
JSON.stringify({
'videoId': videoId,
'position': position
})
);
} catch (error) {
}
}
const result = getPosition(videoId);
console.log('result from saved: ', result);
videoPlayer.currentTime = result.position;
</script>
</body>
</html>