Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

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

1,468 views

Published on

google tag manager, custom listeners, debugging

Published in: Education
  • Be the first to comment

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

  1. 1. Проведем 70 минут с пользой! ● 10 минут теории ● 20 минут делаем Measurement Plan ● 40 минут практики
  2. 2. gtm.april@gmail.com MSKsdh83a_3-23 google.com/tagmanager и google.com/analytics GTM-59L85S UA-61497996-1 Авторизуйтесь Заходите
  3. 3. Немного теории
  4. 4. Структура GTM Контейнер – основной блок кода, хранящий все теги (устанавливается на все страницы сайта) Тег – фрагмент кода, который мы хотим имплементировать на сайте Правило – условие активации тега Макрос – переменные уровня данных
  5. 5. Типы Тегов и Макросов
  6. 6. Google Tag Manager позволяет отслеживать шесть типов событий: Типы событий ✓ Прослушивание кликов (gtm.click) ✓ Прослушивание отправок форм (gtm.formSubmit) ✓ Прослушивание кликов по ссылке (gtm.linkClick) ✓ Прослушивание таймера (gtm.timer) ✓ Обработчик ошибок JavaScript (gtm.pageError) ✓ Обработчик событий истории (gtm.historyChange) + вы можете писать собственные обработчики событий
  7. 7. В кастомных макросах и тегах можно ссылаться на свойства объекта DOM, или сам объект
  8. 8. gtm.element.nodeName Example return value: IMG gtm.element.value Example return value: Simo Ahava What 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.hash Example return value: #chapter1 What 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.pathname Example 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.search Example return value: ?internal=true What 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
  9. 9. Data Layer Variable Name: gtm.element.parentElement Example return value: (object), extend further with some property of the parent element What 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.firstChild Example return value: (object), extend further with some property of the child element What 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.nextSibling Example return value: (object), extend further with some property of the sibling element What 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)
  10. 10. ● 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
  11. 11. 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 value a[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
  12. 12. Что вообще можно делать?
  13. 13. Так выглядят реальные контейнеры И да, там ни строчки кода GA/dataLayer на сайтах. Все отслеживается “снаружи”.
  14. 14. 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+?
  15. 15. 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
  16. 16. ● 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
  17. 17. Вызов транзакции в GA и Метрике одновременно По 1 правилу - два тега 1) сustom html tag <script type="text/javascript"> yaCounter179064.reachGoal('Home', yaParams); </script> 2) тег Google Analytics, тип transaction GTM трюки
  18. 18. GTM трюки - проигрывание видео на сайте
  19. 19. GTM трюки - клики по маркерам на карте
  20. 20. Пример расширенных сегментов ссылка в ротации по clientId.
  21. 21. ClientID traversal http://surveygizmo.com/s3/1933094?sguid=12324233.123123123 Пример расширенных сегментов
  22. 22. Собираем объект для расширенной электронной торговли по кускам
  23. 23. Если товаров много (например, в корзине) 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].innerText products.push({'name':name,'quantity':quantity,'price':price}); }
  24. 24. Отправляем 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...
  25. 25. Делаем из хлебных крошек 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"
  26. 26. Инструменты дебага
  27. 27. Проверка валидности хитов в Measurement Protocol
  28. 28. Google analytics Debugger ● включает расширенный лог в консоль, заменяя analytics.js на analytics_debug.js
  29. 29. Tag Assistant by Google ● показывает какие теги присутствуют на страницах и нет ли синтаксических ошибок ● для GTM контейнеров показывает какие теги были запущены через него.
  30. 30. ● А создался ли сам объект ga? ● Выполняются ли функции?
  31. 31. Если MP отправляется из недоступного вам куска кода
  32. 32. Инструмент отладки 1) Отладчик GTM 2) отчеты Real Time
  33. 33. Какие теги сработали при выполнении действия Инструмент отладки Действие при отладке

×