概要
よくGoogle Tag Managerの設定方法を忘れるので備忘録です。
GAキャンペーンパラメータ Cookie書き込み
<script>
var params = location.search.substring(1).split('&');
for (var i = 0; i < params.length; i++) {
if (params[i].match(/utm_((medium)|(source)|(campaign)|(content))=.*/)) {
document.cookie = params[i] + ';path=/;max-age=' + 1 * 60 * 60 * 24 * 90;
document.cookie = 'lp_url=' + location.protocol + '//' + location.host + location.pathname + ';path=/;max-age=' + 1 * 60 * 60 * 24 * 90;
}
}
</script>
UTMパラメータを含む場合のURLの正規表現
UTMパラメータを含むPage Pathと一致させたい場合、以下のような正規表現で可能。
^/jp/thanks_download(\?.*|#.*)*$
GAのcid取得
変数の設定:ファーストパーティCookie
Cookie名:_ga
Cookieを利用する
確認画面でCVを計測する際に、値を取得できない場合に、Cookieに書き込んで持ち回る。
以下のような処理で値を取得し、Cookieに書き込みを行う。
function(){
var DonationAmontValue;
var selectedValue;
var options;
var pageType;
//対象ページごとに、金額の取得方法を選択
if( {{Page Path}}.match(/^\/index\.php$/) ){
var checkbox = document.frm.Amount;
for (i = 0; i < checkbox.length; i++){
if(checkbox[i].checked){
selectedValue = checkbox[i].value;
break;
}
}
if( typeof parseFloat(selectedValue.trim()) === "number" ){
AmontValue = parseFloat(selectedValue.trim());
}
}
//値を返す
return AmontValue;
}
利用する際は、Cookie変数から値を取得する。
<script>
now = new Date();
var transactionId = {{UA - cid from _ga cookie}} + '-' + now.getTime();
var cartProducts = [];
cartProducts.push({
"id": transactionId,
"name" : "{{Page Path}}",
"price" : "{{Cookie_AmontValue}}",
"quantity" : "1"
});
dataLayer.push({
'event' : 'trackTrans','ecommerce': {
'purchase': {
'actionField': {
'id': transactionId,
'revenue': '{{Cookie_AmountValue}}'
},
'products': cartProducts
}
}
});
//cookieから値を削除
document.cookie = "Contribution=; expires=Thu, 01 Jan 1970 00:00:00 GMT; domain = hoge.com ; path = / ";
</script>
Yahoo広告でのクロスドメイン計測
Yahoo広告を計測するためのGTMの設定について
クロスドメインの設定
カスタムhtmlで以下を設置する。
{{yclid}}はCookieから取得した値。
<script>
if ({{yclid}}){
console.log("yahoo cross domain")
var targets = document.querySelectorAll('a');
for (var i = 0; i < targets.length; i++) {
var target = targets[i];
var url = target.href;
url += '?yclid=' + {{yclid}};
target.href = url;
}
}
</script>
サイトジェネラルタグ
サイトジェネラルタグが発行する前に、クロスドメインタグを有効にする必要がある。
<script async src="https://s.yimg.jp/images/listing/tool/cv/ytag.js"></script>
<script>
window.yjDataLayer = window.yjDataLayer || [];
function ytag() { yjDataLayer.push(arguments); }
ytag({"type":"ycl_cookie"});
</script>
コンバージョン測定タグ
<script async>
window.yjDataLayer = window.yjDataLayer || [];
function ytag() { yjDataLayer.push(arguments); }
ytag({"type":"ycl_cookie"});
ytag({
"type": "yss_conversion",
"config": {
"yahoo_conversion_id": "99999999,
"yahoo_conversion_label": "xxxxxxxxxxxxxxx",
"yahoo_conversion_value": "3000"
}
});
</script>
onclickの計測
onclickでページを遷移する場合、、GTMが発火したとしても先にonclickで呼び出されるJavasceriptの処理が進んでしまい、ページが遷移してしまう。遷移までにタグ発火が間に合わないと、計測できない。
また、「タグの配信を待つ」のオプションはタグのみで有効であり、onclickの場合は使えない。
このような場合に計測するための方法について。
onclickでLinkerParamを付与する
<script>
$(document).ready(function() {
var button = document.querySelector('#btn1');
var oclick = button.getAttribute('onclick');
var href = oclick.match(/'(.+)'/)[1];
button.setAttribute('onclick', '');
button.addEventListener('click', function() {
var linker = window.ga && window.ga.getAll ? window.ga.getAll()[0].get('linkerParam') : '';
window.location.href = linker ? href + '?' + linker : href;
});
});
</script>
HTMLページ生成時にonclickより前に実行する関数を差し込む
prependEvent
prependEvent = function(target, newEvent) {
var clickHandler;
clickHandler = target[0].onclick; // イベントを退避
target[0].onclick = null; // クリックイベントをリセット
target.click(newEvent); // 差し込み
target.click(clickHandler); // その後にオリジナルをしまう
};
↓こんなカンジで使います。
<input id="confirmButton" type="button" onclick="alert('first');" value="test input"/>
secondFunction = function() {
alert("second");
};
prependEvent($("input#confirmButton"), secondFunction);
サブスクストア
コンバージョンタグ
<!-- Global Site Tag (gtag.js) - Google Analytics tamago -->
<script async src="https://www.googletagmanager.com/gtag/js?id=【GAのプロパティID】"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '【GAのプロパティID】', {'page_path': document.location.pathname});
</script>
参考:公式ヘルプ
eコマーストラッキング
<script>
gtag('event', 'purchase', {
"transaction_id": @@order_id@@,
"affiliation": @@shop_name@@,
"value": @@order_total@@.
"tax": @@tax_total@@,
"shipping": @@shipment_total@@,
"items": [
@@item_code@@
]
});
</script>
アイテムコード
{
"id": @@item_sku@@,
"name": @@item_name@@,
"category": @@item_category@@,
"quantity": @@item_quantity@@,
"price": @@item_price@@
},
今後記載したい内容
- シャープ記号(#)付きのURLをGoogleアナリティクスで測定する
- 「スクロール距離」トリガーと「要素の表示」トリガーの使用方法について
- GTMでYouTube動画の計測