tracking embeded youtube videos views

2019-05-13 22:20发布

I have embeded some youtube videos in my website. I want to track the views of each videos with google analytics, but I cannot catch any onClick event because the videos are embeded in using iFrame. How can I track the views of youtube videos that is embeded in my webpage using iFrame ?

1条回答
唯我独甜
2楼-- · 2019-05-13 23:08

I've been using YouTube's API to track plays as events in Google Analytics. It's the same format in iFrame API and javascript. Look at the iFrame API if you want to track other functions. This is where I originally got the event tracking information.

You'll have to change the videoID below:

<div id="player"></div>

<script type="text/javascript">
    var tag = document.createElement('script');
    tag.src = "http://www.youtube.com/player_api";
    var firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
    var player;

    function onYouTubePlayerAPIReady() {
        player = new YT.Player('player', {
            height: '390',
            width: '640',
            videoId: 'fYmrMt01S1U',
            events: {
                'onReady': onPlayerReady,
                'onStateChange': onPlayerStateChange
            }
        });
    }

    function onPlayerReady(event) {
        /// event.target.playVideo(); 
    }

    function onPlayerStateChange(event) {
        if (event.data == YT.PlayerState.PLAYING) {
            _gaq.push(['_trackEvent', 'Videos', 'Play',
            player.getVideoUrl()]);
        }
        if (event.data == YT.PlayerState.PAUSED) {
            _gaq.push(['_trackEvent', 'Videos', 'Paused',
            player.getVideoUrl()]);
        }
        if (event.data == YT.PlayerState.ENDED) {
            _gaq.push(['_trackEvent', 'Videos', 'Watch to End',
            player.getVideoUrl()]);
        }
    }
    // ]]>
</script>
查看更多
登录 后发表回答