javascript 跟踪Google Analytics中的外部文件下载,文件下载和外部链接。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 跟踪Google Analytics中的外部文件下载,文件下载和外部链接。相关的知识,希望对你有一定的参考价值。

// Track external file downloads, file downloads and external links in
// Google Analytics.
//
// Based on:
// http://www.axllent.org/docs/view/track-outbound-links-with-analytics-js/
// 
// Blog post:
// https://labs.kollegorna.se/blog/2015/04/google-analytics-track-external-links-downloads/

function _gaLt(event){
  var el = event.srcElement || event.target;

  // Loop up the tree through parent elements if clicked element is not a link
  // (eg: an image inside a link).
  while (el && (typeof el.tagName == 'undefined' || el.tagName.toLowerCase() != 'a' || !el.href)) {
    el = el.parentNode;
  }

  if (el && el.href) {
    var filetypes = /\.(zip|rar|tar|gz|exe|dmg|pdf|doc.*|xls.*|ppt.*|pps.*|vcf|txt|csv|rtf|odt|pages|mp3|wav|wma|mov|avi|wmv|mpg|mp4|flv|png|jpg|jpeg|gif|tif|tiff|bmp|svg|eps|ai|psd)$/i;
    var referrer = document.location.pathname + document.location.search;
    var open_link = false;

    if (el.href.match(filetypes)) { // File download
      if (el.href.indexOf(location.host) == -1) { // External file
        ga('send', 'event', 'Download external file', el.href, referrer);
      }
      else { // Internal file
        ga('send', 'event', 'Download file', el.pathname, referrer);
      }
      open_link = true;
    }
    else if (el.href.indexOf(location.host) == -1) { // External link
      ga('send', 'event', 'External link', el.href, referrer);
      open_link = true;
    }

    if (open_link) {
      setTimeout(function() {
        window.open(el.href, '_blank');
      }.bind(el), 500);

      event.preventDefault ? event.preventDefault() : event.returnValue = false;
    }
  }
}

// Attach the event to all clicks in the document after page has loaded.
if (window.addEventListener) {
  window.addEventListener('load', function() {
    document.body.addEventListener('click', _gaLt, false);
  }, false);
}
else {
  window.attachEvent && window.attachEvent('onload', function() {
    document.body.attachEvent('onclick', _gaLt);
  });
}

// The same attach code as above, minified for minimalists.
var w=window,b=document.body;w.addEventListener?w.addEventListener('load',function(){b.addEventListener('click',_gaLt,!1)},!1):w.attachEvent&&w.attachEvent('onload',function(){b.attachEvent('onclick',_gaLt)});

以上是关于javascript 跟踪Google Analytics中的外部文件下载,文件下载和外部链接。的主要内容,如果未能解决你的问题,请参考以下文章

javascript Google Analytics事件跟踪Javascript

javascript 使用Google Analytics跟踪JavaScript错误(作为事件)

javascript 使用Google Analytics跟踪JavaScript文件加载时间

javascript 使用事件跟踪和jQuery跟踪Google Analytics中的传出链接

javascript 使用Google的Universal Analytics跟踪JavaScript错误。

javascript 使用Google的Universal Analytics跟踪JavaScript错误。