2012-07-31 33 views
0

我試圖使用gaAddons Google Analytics jQuery plugin來跟蹤我網站上的下載內容,因此任何已下載的.JPG,.PNG,.PDF等都需要執行一些跟蹤代碼來跟蹤。使用jQuery捕獲站點範圍內的文件下載

很明顯,有些東西不能正常工作,因爲我似乎無法啓動_trackEvent

這是駐留在gaAddons插件中的JavaScript。

/////////////////// 
// _trackDownloads 
jQuery(document).ready(function($) { 
    // helper function - allow regex as jQuery selector 
    $.expr[':'].regex = function(e, i, m) { 
     var mP = m[3].split(','), 
      l = /^(data|css):/, 
      a = { 
       method: mP[0].match(l) ? mP[0].split(':')[0] : 'attr', 
       property: mP.shift().replace(l, '') 
      }, 
      r = new RegExp(mP.join('').replace(/^\s+|\s+$/g, ''), 'ig'); 
     return r.test($(e)[a.method](a.property)); 
    }; 

    $('a:regex(href,"\\.(zip|mp\\d+|mpe*g|pdf|docx*|pptx*|xlsx*|jpe*g|png|gif|tiff*)")$').live('click', function(e) { 
     _gaq.push(['_trackEvent', 'download', 'click', this.href.replace(/^.*\/\//, '')]); 
    }); 
}); 

我已經包括在頁面上,上面的代碼和我的簡單的錨鏈接到下面的PDF文件。

<a href="http://www.ayrshireminis.com/downloads/Files/pdfs/turnberry.pdf" target="blank">DOWNLOAD</a> 

是不是有什麼毛病JavaScript,或者是有一個更簡單的檢查JPG/PNG/PDF文件下載方式?我可能會忽略zip/ppt/tiff文件,因爲它們不會在網站上。

回答

1

我身邊有傾斜的幾個小時,跨越這個解決方案來了,希望這可以幫助別人:

jQuery(document).ready(function($) { 
    var filetypes = /\.(zip|exe|pdf|doc*|xls*|ppt*|mp3)$/i; 
    var baseHref = ''; 
    if (jQuery('base').attr('href') != undefined) 
     baseHref = jQuery('base').attr('href'); 
     jQuery('a').each(function() { 
      var href = jQuery(this).attr('href'); 
      if (href && href.match(filetypes)) { 
       jQuery(this).click(function() { 
        var extension = (/[.]/.exec(href)) ? /[^.]+$/.exec(href) : undefined; 
        var filePath = href; 
        _gaq.push(['_trackEvent', 'Download', 'Click-' + extension, filePath]); 
        if (jQuery(this).attr('target') != undefined && jQuery(this).attr('target').toLowerCase() != '_blank') { 
         setTimeout(function() { location.href = baseHref + href; }, 200); 
         return false; 
        } 
       }); 
      } 
     }); 
}); 
+0

嘿,這是偉大的。它不久前,但你還記得這段代碼片段的來源嗎? – 2013-10-07 12:10:06

+1

@JakeB。對不起,傑克。我不。前段時間我完成了這個項目,但我記得這段代碼對我很好。 – crmpicco 2013-10-07 13:19:52

+0

沒問題,只是好奇!我正在嘗試一下,看看做我需要的東西。謝謝! – 2013-10-08 01:10:24