特定class名にイベントトラッキング(私用版
あるclass名がついたリンクにGoogle Analyticsのイベントトラッキングをいれるというもの。
自分でだましだまし使っている状態なので、動作は保証できませんが。
外部スクリプトファイルで読み込ませてその中身。
(function (){ var a = document.getElementsByTagName('a'); for (var i=0; i<a.length; i++) { if (a[i].className=='event_link') { a[i].addEventListener ? a[i].addEventListener( 'click' , tkevent_link , false ):a[i].attachEvent('onclick',tkevent_link); } if (a[i].className=='event_file') { a[i].addEventListener ? a[i].addEventListener( 'click' , tkevent_file , false ):a[i].attachEvent('onclick',tkevent_file); } } function tkevent_link(){ try { var that=this; _gaq.push(['_trackEvent','link','external', this.href ]); setTimeout(function(){window.location.href=that.href}, 300) }catch(err){}; return false; } function tkevent_file(){ try { var that=this; _gaq.push(['_trackEvent','download','file', this.href ]); setTimeout(function(){window.location.href=that.href}, 300) }catch(err){}; return false; } })()
外部リンクなときに、event_linkとclassを振った場合にイベントにあわせたトラッキングを実行という形。href属性がある場合にタイミングでトラッキングがおこなえないことがあるので、setTimeoutでページ移動を遅らせてみたり。タイマーの値が大きすぎると、ファイルなど2重ダウンロードになるので注意
追記
割り込み時間が短すぎてもだめなときがあるようなので様子見で。冗長な感じはするけどダウンロードファイルは特にページ遷移をおこさないようにしてみたり。外部ページのほうは一旦hrefを削除してそもそものリンクが先に移動しないような感じに。href属性値が無しというか'#'とか'javascript:'のようなhttpでないようなのでないと正確に計測できないような気がします。
(function (){ var a = document.getElementsByTagName('a'); for (var i=0; i<a.length; i++) { if (a[i].className=='event_link') { a[i].addEventListener ? a[i].addEventListener( 'click' , recordOutboundLink, false ):a[i].attachEvent('onclick',recordOutboundLink); } if (a[i].className=='event_file') { a[i].addEventListener ? a[i].addEventListener( 'click' , tkevent_file , false ):a[i].attachEvent('onclick',tkevent_file); } } function tkevent_file(){ try { if(window.event.srcElement){ var that = event.srcElement.href; } else { var htat=this.href; }; _gaq.push(['_trackEvent','download','file',that]); setTimeout(function(){return;},300); }catch(err){}; } function recordOutboundLink() { try { var msie = navigator.appVersion.toLowerCase(); msie=(msie.indexOf('msie')>-1)?parseInt(msie.replace(/.*msie[ ]/,'').match(/^[0-9]+/)):0; // Browser checker if(msie<9 && msie!=0){ var that = event.srcElement.href; } else { var that=this.href; }; _gaq.push(['_trackEvent','link','external',that]); this.removeAttribute('href'); setTimeout(function(){ location.href=that; }, 800); }catch(err){} } })() // 111007 www.markdiary.com // Browser Checher by http://www.losttechnology.jp/WebDesign/2011/ieversion.html
IE 8以下でthatの値がとれないようなので event.srcElementを使ってみることに。Safari Opera Chromeが対応しているようで、window.event.srcElement?
で振り分けてもいいのかな、という気がしないでもないけどいちおう。
Trackbacks:0
- TrackBack URL for this entry
- https://www.markdiary.com/mt/app-pingback.cgi/67
- Listed below are links to weblogs that reference
- 特定class名にイベントトラッキング(私用版 from maRk lab
Comments:0