是否只有初始视频播放的onStateChange事件?

时间:2014-03-07 20:44:06

标签: javascript jquery youtube-api click-tracking

立即尝试在初始视频播放中实施Google跟踪。

API给出6个州,

-1 (unstarted)
0 (ended)
1 (playing)
2 (paused)
3 (buffering)
5 (video cued).

但我正在使用的状态(1:播放)会在每次视频点击时触发。我只想跟踪最初的比赛事件。

这是我到目前为止所做的。

asyncYouTubeApiLoad();
getVideoTrackingValues();


function getVideoTrackingValues() {
    $player = $('#player'),
    $yt_trackValue = $player.data('tracking-value');
}

executeYouTubeReady();

function executeYouTubeReady() {
    // Wait for API
    setTimeout(function() {
        onYouTubeIframeAPIReady();
    }, 200);
}

function onYouTubeIframeAPIReady() {
  player = new YT.Player('player', {
    events: {
      'onStateChange': onPlayerStateChange
    }
  });
}

function onPlayerStateChange(event) {
    // On Play
    if (event.data = 1) {
        fireVideoEventTracking('video_play');
    }
    // On End
    else if (event.data = 0) {
        fireVideoEventTracking('video_complete');
    }
}

function fireVideoEventTracking(eventType) {
    _gaq.push(['_trackEvent', 'video', eventType, $yt_trackValue]);                    
}

1 个答案:

答案 0 :(得分:1)

结束向onReady方法添加一个布尔值并检查它。

var initialLoad = false;

    function onYouTubeIframeAPIReady() {
      player = new YT.Player('player', {
        events: {
          'onReady': onPlayerReady,
          'onStateChange': onPlayerStateChange
        }
      });
    }

    function onPlayerReady() {
        initialLoad = true;
    }

    function onPlayerStateChange(event) {
        console.log(event.data);
        // On Play
        if (event.data == 1 && initialLoad) {
            fireVideoEventTracking('video_play');
            initialLoad = false;
        } else if (event.data == 0) {
            fireVideoEventTracking('video_complete');
        }
    }