Google Analyticsのトラッキングコードを遷移先で除去する
Google Analyticsではutm_source
などのutm_*
を付けると管理画面上でよしなにまとめてくれるので大変便利なのですが、
URLが汚染されてしまう。
http://example.com/archives/1234?utm_source=twitter&utm_medium=h3ntaikun
こんなの。
表示だけなら見栄えの問題で済むんだけど、これがファーストビューでアクトレ先に流れると……
という残念仕様になるので何とかしたい。
方法
既にやっている人がいたので、基本このまま。
しかし、
ソース長いぉ……
// ここ以下が、トラッキングパラメータの処理 // gaのキューに処理を突っ込む // (pageviewとかのURLはcreate時に確定してる) ga(function(){ // hisotry APIをサポートしているブラウザでのみ実行 if (window.history && window.history.replaceState) { do_replaceState = false; // replaceStateするかどうかのフラグ var url,query_string,hash,matches,domain,path; // 各種処理変数 var queries = []; // replaceState時に使うquery string // utm系のリスト(+FBのやつも) var utms = { utm_source : true, utm_medium : true, utm_term : true, utm_content : true, utm_campaign : true, fb_action_ids : true, fb_action_types : true, fb_source : true, action_object_map : true, action_type_map: true, action_ref_map: true }; // document.locationを使わずに自力でURL解析 url = document.location.toString(); if (matches = url.match(/(.+?)#(.+)/)) { url=matches[1]; hash=matches[2]; } if (matches = url.match(/(.+?)\?(.+)/)) { url=matches[1]; query_string=matches[2]; } // URLにquery stringがあれば、utm系の存在をチェック if (query_string) { query_string = query_string.split(/&/); for (var i =0; i < query_string.length; i++) { var param = query_string[i].split(/=/); if (typeof utms[param[0]] != 'undefined') { // utm系のが1つでもあればreplaceStateフラグをオンに do_replaceState = true; } else { // utm系でなければreplaceState後のURLにも必要 queries.push(query_string[i]); } } } // utm系のパラメータがあれば、それを除いたURLにreplaceState if (do_replaceState) { // replaceState先の指定 if (queries.length){ url += '?' + queries.join("&"); } if (hash){ url += '#' + hash; } // replaceState history.replaceState('', '', url); } } });
えっと、もっと短くなりませんかね?
なるでしょう!
ということで、書き直す。
書き直した版
// トラッキングパラメータの除去 if (window.history && window.history.replaceState) { ga(function() { var params = [ 'utm_source', 'utm_medium', 'utm_term', 'utm_content', 'utm_campaign', 'fb_action_ids', 'fb_action_types', 'fb_source', 'action_object_map', 'action_type_map', 'action_ref_map' ]; var regexp = new RegExp('(?:' + params.join('|') + ')=.+?(?:&|#|$)', 'g'); var trimUrl = document.location.href.replace(regexp, '').replace(/[\?&]#/, '#').replace(/[\?&]$/, ''); if (document.location.href != trimUrl) { window.history.replaceState('', '', trimUrl); } }); }
元のものは引数を自前でバラすということをやっていたのですが、 値を見て動作を変えることはなさそうなので、ばっさりreplaceしちゃってます。
あとは、history関数が使えない場合はgaのイベント登録する必要もないので、とか細かい所を直しました。
あんまりテストしてないけど、動いてるっぽいのでうちはこれで。