Book – Code Examples
Here are some of the code examples included in the second edition of the book.
Please take a moment to test code before it's applied to your live website to ensure it works as expected.
Chapter 19
Modified Google Optimize code for use with Google Tag Manager:
<HTML><HEAD><!-- Start Google Optimize --><style>.async-hide { opacity: 0 !important} </style><script>(function(a,s,y,n,c,h,i,d,e){s.className+=' '+y;h.start=1*new Date;h.end=i=function(){s.className=s.className.replace(RegExp(' ?'+y),'')};(a[n]=a[n]||[]).hide=h;setTimeout(function(){i();h.end=null},c);h.timeout=c;})(window,document.documentElement,'async-hide','dataLayer',4000,{'GTM-EDCBA':true});</script><!-- Modified GA tracking for Optimize --> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','https://www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-123456-1', 'auto'); ga('require', 'GTM-EDCBA');</script><!-- End Google Optimize -->
Standard Google Tag Manager code (which would be placed below the Google Optimize code):
<!-- Google Tag Manager --><script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src='https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);})(window,document,'script','dataLayer','GTM-ABCDE');</script><!-- End Google Tag Manager -->
Chapter 22
Example of event tracking that has been hard-coded within a specific link:
<div class="banner-promotion"><a href="/free-trial" onClick="ga('send', 'event', 'Internal Promotion', 'Banner Image', 'Free Trial Offer', 5);"><img src="/images/banners/free-trial.png" /><img … /></a></div>
Custom HTML tag for use with Google Tag Manager to track promotion views (impressions):
<script>(function() { dataLayer.push({ 'event': 'my-promotion-impression', 'ecommerce': { 'promoView': { 'promotions': [ { 'id': 'promotion1234', 'name': 'Spring Features', 'creative': 'Green Shirts', 'position': '1' }] } } });}());</script>
Custom HTML tag for use with Google Tag Manager when a promotion is clicked:
<script>(function() { dataLayer.push({ 'event': 'my-promotion-click', 'ecommerce': { 'promoClick': { 'promotions': [ { 'id': 'promotion1234', 'name': 'Spring Features', 'creative': 'Green Shirts', 'position': '1' }] } } });}());</script>
Example of using custom parameters to track promotions:
<a href="/free-trial?in_type=banner-image&in_name=free-trial"><img src="/images/banners/free-trial.png" alt="Free Product Trial Offer" /></a>
Chapter 24
Regular Expression to find default pages:
^(/(index|default|home)?\.?(html|htm|php|asp|aspx|jsp)?)$
Chapter 28
Example code for tracking users between two websites:
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-123456-1"></script>
<script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments)}; gtag('js', new Date()); gtag('config', 'UA-123456-1', { 'linker': {'domains': ['company.com', 'other.com'] } });</script>Example of event tracking that has been hard-coded within a specific link to download a PDF:
<a href="/files/information.pdf" onclick="gtag('event', 'event_name', {'event_category': 'download', 'event_action': 'pdf', 'event_label': 'information.pdf'});">Download Information PDF</a>
Example of event tracking that has been hard-coded within a specific link to download a Document:
<a href="/files/information.pdf" onclick="gtag('event', 'event_name', {'event_category': 'download', 'event_action': 'doc', 'event_label': 'application.doc'});">Download Application Document</a>
Event tracking example:
gtag('event', 'event_name', {'event_category': 'your category','event_action': 'your action','event_label': 'your label','value': 4});
Event tracking example with a 'non-interaction' hit type:
gtag('event', 'event_name', {'event_category': 'your category','event_action': 'your action','event_label': 'your label','value': 4,'non_interaction': true});
Example of the default Google Analytics tracking code:
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-123456-1"></script><script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments)}; gtag('js', new Date()); gtag('config', 'UA-123456-1');</script>
Example of tracking code that is modified to track an ecommence transaction:
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-123456-1"></script>
<script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments)}; gtag('js', new Date()); gtag('config', 'UA-123456-1'); gtag('event', 'purchase', { "transaction_id": "TID654321", "value": 39.99, "currency": "USD", "tax": 3.19, "shipping": 4.95, "items": [{ "name": "Branded Tshirt", "category": "Apparel", "variant": "Red", "quantity": 1, "price": 19.95},{ "name": "Mens Socks", "category": "Apparel", "variant": "Blue", "quantity": 2, "price": 5.95} ] });</script>Example of a data layer for tracking transactions into Google Tag Manager:
<script>window.dataLayer = window.dataLayer || [];dataLayer.push({ 'ecommerce': { 'purchase': { 'actionField': { 'id': 'TID654321', 'revenue': '39.99', 'tax': '3.19', 'shipping': '4.95' }, 'products': [{ 'id': 'PID765123', 'name': 'Branded Tshirt', 'category': 'Apparel', 'variant': 'red', 'price': '19.95', 'quantity': 1 }, { 'id': 'PID123445', 'name': 'Mens Socks', 'category': 'Apparel', 'variant': 'blue', 'price': '5.95', 'quantity': 2 }] } }});</script><!-- Google Tag Manager --><script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src='https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);})(window,document,'script','dataLayer','GTM-AB1EF2');</script><!-- End Google Tag Manager -->
Example of tracking code that is modified to track a custom dimension:
gtag('config', 'UA-123456-1', { 'custom_map': {'dimension1': 'author'}});gtag('event', 'author_dimension', {'author': 'Jessica'});
Example of correctly modified tracking code that tracks an event:
gtag('config', 'UA-123456-1');gtag('event', 'event_name', {'event_category': 'promotion','event_action': 'featured product',});
Example of correctly modified tracking code to track data into two separate accounts:
gtag('config', 'UA-123456-1');gtag('config', 'UA-654321-1');
Chapter 29
Regular Expression to track some clicks in Google Tag Manager:
\.(pdf|docx?|zip|xlsx?|pptx?|exe|txt)$
Custom JavaScript code to track YouTube video actions in Google Tag Manager:
function() { var status = {{Video Status}}; switch (status) { case 'start': return 'Play'; case 'pause': return 'Pause'; case 'seek': return 'Seeking'; case 'progress': return + {{Video Percent}} + '% Watched'; case 'complete': return '100% Watched'; }}