Skip to content

Instantly share code, notes, and snippets.

@Elyorbe
Last active December 24, 2022 01:49
Show Gist options
  • Save Elyorbe/9efa78bfba156956f5cfc9afdee71b07 to your computer and use it in GitHub Desktop.
Save Elyorbe/9efa78bfba156956f5cfc9afdee71b07 to your computer and use it in GitHub Desktop.
console.log("___________TRACKING______________");
const iframe = document.getElementsByTagName('iframe')[0]
const myPlayer = new Vimeo.Player(iframe);
// const iframe = null;
if (iframe) {
console.log('[elyor] iframe exists');
const player = new Vimeo.Player(iframe);
const url = iframe.getAttribute("src").split('?')[0];
const vimeoId = extractVimeoId(url);
fetchLastWatchProgress(vimeoId).then((data) => {
console.log("[elyor] Promise fetch: ", data);
return setPlayerTime(player, data.progress);
});
// trackWatchProgress(vimeoId, player);
}
function fetchLastWatchProgress(vimeoId) {
console.log('[elyor] fetchLastWatchProgress()');
return new Promise((resolve, reject) => {
jQuery.ajax({
url: ajaxurl,
data: {
'action': 'last_watch_progress_request',
'video_id': vimeoId
},
success: function (data) {
resolve(data)
},
error: function (error) {
reject(error)
},
});
});
}
function setPlayerTime(player, lastWatchProgress) {
console.log("[elyor] setPlayerTime()");
setTimeout(() => {
player.setCurrentTime(lastWatchProgress).then(function (seconds) {
console.log("[elyor] player.setCurrentTime: ", seconds);
}).catch(function (error) {
switch (error.name) {
case 'RangeError':
console.log("Seconds must be greater than 0")
break;
default:
console.log("Error: ", error)
break;
}
});
console.log("[elyor] TIMEOUT RUN");
}, 3000);
}
function trackWatchProgress(vimeoId, player) {
console.log("[elyor] trackWatchProgress");
setInterval(function () {
player.getCurrentTime().then(function (seconds) {
console.log("[elyor] player.getCurrentTime", seconds);
sendProgressToServer(vimeoId, seconds);
});
}, 5000);
}
function extractVimeoId(url) {
const vimeoRegex = /https?:\/\/(?:www\.)?(vimeo.com|player.vimeo.com)\/(?:(channels|video)\/(?:\w+\/)?|groups\/([^\/]*)\/videos\/|album\/(\d+)\/video\/|)(\d+)(?:$|\/|\?)/;
const match = url.match(vimeoRegex);
if (match) return match[5];
}
function sendProgressToServer(videoId, progress) {
console.log("[elyor] sendProgressToServer()");
jQuery.ajax({
url: ajaxurl,
data: {
'action': 'last_watch_progress_update',
'video_id': videoId,
'progress': progress
},
success: function (response) {
console.log("[elyor] response from sending progress to server: ", response);
},
error: function (errorThrown) {
console.log("Error while sending watch progress: ", errorThrown);
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment