How can I track a click event of an embedded video (youtube, vimeo, etc.)? (to track play count)

非 Y 不嫁゛ 提交于 2019-11-29 04:39:04
Kevin Pei

Ryan, the only way to do this is to use the video sharing site's player api(s), as html and javascript have no native support for this.

To do this for youtube videos, you can check out the documentation here

To do this for vimeo videos, you can check out the documentation here

This works for Vimeo... Triggers a javascript alert on the "Play" event but there are a number of other events like "finished", "pause", "playProgress" (constantly updating while video is playing)... Uses Jquery

$(document).ready( function () {

var f = $('iframe'),
    url = f.attr('src').split('?')[0],
    status = $('.status');

// Listen for messages from the player
if (window.addEventListener){
    window.addEventListener('message', onMessageReceived, false);
}
else {
    window.attachEvent('onmessage', onMessageReceived, false);
}

// Handle messages received from the player
function onMessageReceived(e) {
    var data = JSON.parse(e.data);

    switch (data.event) {
        case 'ready':
            onReady();
            break;

        case 'play':
            onPlay();
            break;

    }
}

// Call the API when a button is pressed
$('button').on('click', function() {
    post($(this).text().toLowerCase());
});

// Helper function for sending a message to the player
function post(action, value) {
    var data = { method: action };

    if (value) {
        data.value = value;
    }

    f[0].contentWindow.postMessage(JSON.stringify(data), url);
}

function onReady() {
    status.text('ready');
    post('addEventListener', 'play');
}

function onPlay() {
        alert("Dude done clicked 'Play'");
}

});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!