2018-07-19

How to Track YouTube Player Events in Google Analytics


iframe - 這是直接以 YouTube 嵌入的方式
 -

player_api - 這是舊版的 play_api 與 GA 事件追蹤


iframe_api  - 這是新版的 iframe_api 與 GA 事件追蹤


iframe_api  - HTML 語法如下
======================
<div id="youTubePlay"></div>
<script>
  var tag = document.createElement('script');
  tag.src = "http://www.youtube.com/iframe_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

  function onYouTubeIframeAPIReady(event) {
    player = new YT.Player('youTubePlay', {
      height: '480',
      width: '720',
      videoId: '5NtobRlZMlU',
    playerVars: {
      rel: 0,
      autoplay: 0,
      disablekb: 0,
      showsearch: 0,
      showinfo: 0,
      controls: 1,
      wmode: 'opaque',
      hd: 1,
      html5: 1,
      iv_load_policy: 3
      },
    events: {
      'onReady': PlayerReady,
      'onStateChange': PlayerStateChange
      }
    });
  }
  function PlayerReady(event) {
  }
    var pauseFlag = false;
    function PlayerStateChange(event) {
      if (event.data == YT.PlayerState.PLAYING) {
        gtag('event', 'Videos', {
          'event_category': 'Playing',
          'event_label': '5NtobRlZMlU',
          'value': 1
        });
        pauseFlag = true;
      }
      if (event.data == YT.PlayerState.PAUSED && pauseFlag) {
        gtag('event', 'Videos', {
          'event_category': 'Pause',
          'event_label': '5NtobRlZMlU',
          'value': 0
        });
        pauseFlag = false;
      }
      if (event.data == YT.PlayerState.ENDED) {
        gtag('event', 'Videos', {
          'event_category': 'Ended',
          'event_label': '5NtobRlZMlU',
          'value': 10
        });
      }
    }
</script>

沒有留言:

張貼留言