Мастеркласс по gtm на google event

40
Проведем 70 минут с пользой! 10 минут теории 20 минут делаем Measurement Plan 40 минут практики

Upload: kirill-bushev

Post on 27-Jul-2015

313 views

Category:

Education


3 download

TRANSCRIPT

Page 1: Мастеркласс по GTM на Google Event

Проведем 70 минут с пользой!● 10 минут теории● 20 минут делаем Measurement Plan● 40 минут практики

Page 2: Мастеркласс по GTM на Google Event

[email protected]_3-23

google.com/tagmanager и google.com/analytics

GTM-59L85S UA-61497996-1

Авторизуйтесь

Заходите

Page 3: Мастеркласс по GTM на Google Event

Немного теории

Page 4: Мастеркласс по GTM на Google Event

Структура GTMКонтейнер – основной блок кода, хранящий все теги (устанавливается на все страницы сайта)

Тег – фрагмент кода, который мы хотим имплементировать на сайте

Правило – условие активации тега

Макрос – переменные уровня данных

Page 5: Мастеркласс по GTM на Google Event

Типы Тегов и Макросов

Page 6: Мастеркласс по GTM на Google Event

Google Tag Manager позволяет отслеживать шесть типов событий:

Типы событий

✓ Прослушивание кликов (gtm.click)

✓ Прослушивание отправок форм (gtm.formSubmit)

✓ Прослушивание кликов по ссылке (gtm.linkClick)

✓ Прослушивание таймера (gtm.timer)

✓ Обработчик ошибок JavaScript (gtm.pageError)

✓ Обработчик событий истории (gtm.historyChange)

+ вы можете писать собственные обработчики событий

Page 7: Мастеркласс по GTM на Google Event

В кастомных макросах и тегах можно ссылаться на свойства объекта DOM, или сам объект

Page 8: Мастеркласс по GTM на Google Event

gtm.element.nodeNameExample return value: IMG

gtm.element.valueExample return value: Simo AhavaWhat it does: Returns the value of the element. This is useful if you’re tracking input elements on your forms (with e.g. blur, focus, or change), and you want to send an event every time a form field has been filled.

Data Layer Variable Name: gtm.element.hashExample return value: #chapter1What it does: Returns the hash (if any) of the element href. So if the link was to /this-page/?internal=true#chapter1, gtm.element.hash would return #chapter1

Data Layer Variable Name: gtm.element.pathnameExample return value: /this-page/What it does: Returns the path in the element href. If the link was to /this-page/?internal=true#chapter1, gtm.element.pathname would return /this-page/

Data Layer Variable Name: gtm.element.searchExample return value: ?internal=trueWhat it does: Returns the full query string of the element. If the link was to /this-page/?internal=true#chapter1, gtm.element.search would return ?internal=true

Переменные типа dataLayer

Page 9: Мастеркласс по GTM на Google Event

Data Layer Variable Name: gtm.element.parentElementExample return value: (object), extend further with some property of the parent elementWhat it does: Returns the direct parent of the element, and you should extend this macro further to access its properties (e.g. gtm.element.parentElement.id returns the value stored in the ID attribute of the parent tag)

Data Layer Variable Name: gtm.element.firstChildExample return value: (object), extend further with some property of the child elementWhat it does: Returns the first direct descendant of the element, and you should extend this macro further to access its properties (e.g. gtm.element.firstChild.className returns value stored in the CLASS attribute of the child tag)

Data Layer Variable Name: gtm.element.nextSiblingExample return value: (object), extend further with some property of the sibling elementWhat it does: Returns the next element in the DOM tree which is on the same hierarchical level as the element, and you should extend this macro further to access its properties (e.g. gtm.element.nextSibling.nodeName returns the tag name of the sibling tag)

Page 10: Мастеркласс по GTM на Google Event

● beforeunload – Fire a listener when the window, the document, and all resources are about to be unloaded (e.g. when someone is closing the browser window).

● blur – An element has lost focus (e.g. the user has left a form field). Note, this doesn’t bubble by default, meaning a listener on the document node won’t be able to catch it. To activate event delegation, you’ll need to set the last parameter in thedocument.addEventListener() call to true instead of false.

● change – The value of an element changes between receiving and losing focus (e.g. the user enters a form field, types something in, and leaves the field).

● click – A click is registered on an element (use GTM’s Click Listener instead).

● contextmenu – The right mouse button is clicked.● copy – Text is copied to the clipboard.● cut – Text is cut to the clipboard.● dblclick – A double-click is registered on an element.● focus – An element has received focus (e.g. the user has left a

form field). Note, this doesn’t bubble by default, meaning a listener on the document node won’t be able to catch it. To activate event delegation, you’ll need to set the last parameter in thedocument.addEventListener() call to true instead of false.

● keydown – A key is pressed down.● keyup – A pressed down key is released.

● mousedown – The mouse button is pressed down.● mouseenter – The mouse pointer is moved over the element

where the listener is attached. Won’t really work if the listener is on the document node.

● mouseleave – The mouse pointer is moved off the element where the listener is attached. Won’t really work if the listener is on the document node.

● mouseout – The mouse pointer is moved off the element where the listener is attached or one of its children.

● mouseover – The mouse pointer is moved over the element where the listener is attached or one of its children.

● mouseup – The pressed down mouse button is released.● orientationchange – The orientation (portrait / landscape) of

the screen changes.● reset – A form is reset.● scroll – A document view or element is scrolled.● submit – A form submit is registered (use GTM’s Form

Submit Listener instead).

<script>

var eventType = "change"; // Modify this to reflect the event type you want to listen for

if (document.addEventListener) {

document.addEventListener(eventType, {{generic event handler}}, false);

} else if (document.attachEvent) {

document.attachEvent('on' + eventType, {{generic event handler}});

}

</script>

https://developer.mozilla.org/en-US/docs/Web/Events

Page 11: Мастеркласс по GTM на Google Event

CSS Selectors rules (GTM v2 only)

.thisclass Matches if element has class “thisclass”

.thisclass.thatclass Matches if element has class “thisclass” and class “thatclass”#thisid Matches if element has ID “thisid”#main .navlink Matches if element has class “navlink” and is a descendant of an element with the ID “main”div#main > .navlink Matches if element has class “navlink” and is the direct child of a DIV element with the ID “main”:checked Matches if element is checked (radio button or checkbox)[data-title~=”chairman mao”] Matches if element has attribute “data-title” with the string “chairman mao” somewhere in its valuea[href$=”.pdf”] Matches if element is a link (A) with a HREF attribute that ends with “.pdf”.contactmail:only-child Matches if element has class “contactmail” and is the only child of its parent

http://www.w3schools.com/cssref/css_selectors.asp

Page 12: Мастеркласс по GTM на Google Event

Что вообще можно делать?

Page 13: Мастеркласс по GTM на Google Event

Так выглядят реальные контейнеры

И да, там ни строчки кода GA/dataLayer на сайтах. Все отслеживается “снаружи”.

Page 14: Мастеркласс по GTM на Google Event

GTM трюкиCustom HTML tag fired on GTM load

<script>var checkzoom = function(e) {

if( e.which === 187 && e.ctrlKey ) { dataLayer.push({'event': 'zoom'}); }

};document.addEventListener('keydown', checkzoom);

</script>

Начиная с какого разрешения экрана пользователи разного возраста пользуются CTRL+?

Page 15: Мастеркласс по GTM на Google Event

MAILTO + &cid on Google Apps Gmail

Revenue from the mailto: links

MP: http://www.google-analytics.com/collect?v=1&tid=UA-8202998-27&t=event&cid=1732166662.1421823610&ec=client&ea=new&ev=3420000

Page 16: Мастеркласс по GTM на Google Event

● top - Detail view● 500px - Checkout● end of the article - Transaction

jQuery custom listener + chain of events + custom html datalayer pushes + enhanced ecommerce tags

Custom Scroll Listener

Page 17: Мастеркласс по GTM на Google Event

Вызов транзакции в GA и Метрике одновременно

По 1 правилу - два тега

1) сustom html tag

<script type="text/javascript">yaCounter179064.reachGoal('Home', yaParams);</script>

2) тег Google Analytics, тип transaction

GTM трюки

Page 18: Мастеркласс по GTM на Google Event

GTM трюки - проигрывание видео на сайте

Page 19: Мастеркласс по GTM на Google Event

GTM трюки - клики по маркерам на карте

Page 20: Мастеркласс по GTM на Google Event

Пример расширенных сегментов

ссылка в ротации по clientId.

Page 21: Мастеркласс по GTM на Google Event

ClientID traversalhttp://surveygizmo.com/s3/1933094?sguid=12324233.123123123

Пример расширенных сегментов

Page 22: Мастеркласс по GTM на Google Event
Page 23: Мастеркласс по GTM на Google Event

Собираем объект для расширенной электронной торговли по кускам

Page 24: Мастеркласс по GTM на Google Event

Если товаров много (например, в корзине)

var products = new Array();for(var i=2; i<document.getElementsByClassName("sale_basket_basket zero")[0].getElementsByTagName("tr").length-1; i=i+3) {

var b=document.getElementsByClassName("sale_basket_basket zero")[0].children[0].children[i];var name = b.children[0].getElementsByClassName("m5")[0].innerText;var quantity = b.getElementsByClassName("quantity")[0].children[0].value;var price = b.getElementsByClassName("price")[0].innerTextproducts.push({'name':name,'quantity':quantity,'price':price});}

Page 25: Мастеркласс по GTM на Google Event

Отправляем Product Impression с указанием списка (также покупают, подойдут) по мере попадания продукта в зону видимости

var productPosition=0;

$(window).bind("scroll", function() { $(".name_carousel:in-viewport").not('.impressionSent').each(function(){ $(this).addClass('impressionSent'); productPosition=productPosition+1; dataLayer.push({'event': 'impression','list' : $(this)[0].parentElement.parentElement.parentElement.className

});

(function($) { $.belowthefold = function(element, settings) { var fold = $(window).height() + $(window).scrollTop(); return fold <= $(element).offset().top - settings.threshold; }; $.abovethetop = function(element, settings) { var top = $(window).scrollTop(); return top >= $(element).offset().top + $(element).height() - settings.threshold; }; $.rightofscreen = function(element, settings) { var fold = $(window).width() + $(window).scrollLeft(); return fold <= $(element).offset().left - settings.threshold; }; $.leftofscreen = function(element, settings) { var left = $(window).scrollLeft(); return left >= $(element).offset().left + $(element).width() - settings.threshold; }; $.inviewport = function(element, settings) { return !$.rightofscreen(element, settings) && !$.leftofscreen(element, settings) && !$.belowthefold(element, settings) && !$.abovethetop(element, settings); }; $.extend($.expr[':'], { "below-the-fold": function(a, i, m) { return $.belowthefold(a, {threshold : 0}); }, "above-the-top": function(a, i, m) { return $.abovethetop(a, {threshold : 0}); }, "left-of-screen": function(a, i, m) { return $.leftofscreen(a, {threshold : 0}); }, "right-of-screen": function(a, i, m) { return $.rightofscreen(a, {threshold : 0}); }, "in-viewport": function(a, i, m) { return $.inviewport(a, {threshold : 0}); } });

})(jQuery);

Visibility обработчик

etc...

Page 26: Мастеркласс по GTM на Google Event

Делаем из хлебных крошек Enhanced E-commerce Product Category

document.getElementsByClassName("breadcrumbs")[0].innerText

"Главная > Каталог > Шторы > В гостиную > Комплект штор для гостиной Antonio-S 123206770"

document.getElementsByClassName("breadcrumbs")[0].innerText.replace(/\s>\s/g ,'/').replace("Главная/Каталог/","");

"Шторы/В гостиную/Комплект штор для гостиной Antonio-S 123206770"

Page 27: Мастеркласс по GTM на Google Event

Инструменты дебага

Page 28: Мастеркласс по GTM на Google Event

Проверка валидности хитов в Measurement Protocol

Page 29: Мастеркласс по GTM на Google Event

Google analytics Debugger

● включает расширенный лог в консоль, заменяя analytics.js на analytics_debug.js

Page 30: Мастеркласс по GTM на Google Event

Tag Assistant by Google

● показывает какие теги присутствуют на страницах и нет ли синтаксических ошибок

● для GTM контейнеров показывает какие теги были запущены через него.

Page 31: Мастеркласс по GTM на Google Event
Page 32: Мастеркласс по GTM на Google Event
Page 33: Мастеркласс по GTM на Google Event

● А создался ли сам объект ga?● Выполняются ли функции?

Page 34: Мастеркласс по GTM на Google Event

Если MP отправляется из недоступного вам куска кода

Page 35: Мастеркласс по GTM на Google Event
Page 36: Мастеркласс по GTM на Google Event
Page 37: Мастеркласс по GTM на Google Event

Инструмент отладки

1) Отладчик GTM

2) отчеты Real Time

Page 38: Мастеркласс по GTM на Google Event

Какие теги сработали при выполнении действия

Инструмент отладкиДействие при отладке

Page 39: Мастеркласс по GTM на Google Event
Page 40: Мастеркласс по GTM на Google Event