Skip to content

Instantly share code, notes, and snippets.

@tfayyaz
Last active August 29, 2015 13:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tfayyaz/19aa32ae4d5a2dc98a5b to your computer and use it in GitHub Desktop.
Save tfayyaz/19aa32ae4d5a2dc98a5b to your computer and use it in GitHub Desktop.

Testing GTM Before Implementing

Using TamperMonkey you can replicate implementing GTM on any website. I like to test on the John Lewis website as they do not have GTM or Universal Analytics so this avoids any code conflicts

// ==UserScript==
// @name       John Lewis Google Tag Manager Demo
// @namespace  http://www.johnlewis.com/
// @version    0.1
// @description  Code to run Google Tag Manager on John Lewis 
// @include      *johnlewis*
// @copyright  2014+, Tahir Fayyaz - tfayyaz.com
// ==/UserScript==

var actualCode = '(' + function() {
    // All code is executed in a local scope.
    // To overwrite a global variable, prefix `window`:

// use http://jsonmate.com/ to create a json dataLayer    
    
if (location.pathname === '/'){
    
window.dataLayer = [{
    "page": {
        "type": "home",
        "url": "/"
    }
}];
    
} else if (location.pathname === '/men/c50000300') {
        
window.dataLayer = [
    {
        "page": {
            "type": "department-landing",
            "url": "/men/c50000300"
        },
        "product": {
            "category": "mens"
        }
    }
];   

} else if (location.pathname === '/men/new-in/c600001949') {
        
window.dataLayer = [
    {
        "page": {
            "type": "category-listings",
            "url": "/men/new-in/c600001949"
        },
        "product": {
            "category": "mens new-in"
        },
        "listingProducts": [
        {
            "id":"123",
            "name": "Ted Baker Treeber Cotton Check Shorts", 
            "category": "mens new-in",
            "price": 55.00,
            "variant": "blue"
        },
        {
            "id":"124",
            "name": "Ted Baker Treeber Cotton Check Shorts", 
            "category": "mens new-in",
            "price": 55.00,
            "variant": "green"
        }]
    }
];   

} else if (location.pathname === '/ted-baker-treeber-cotton-check-shorts-blue/p1265178') {
        
window.dataLayer = [
    {
        "page": {
            "type": "product",
            "url": "/men/new-in/c600001949"
        },
        "product": {
            "id":"123",
            "name": "Ted Baker Treeber Cotton Check Shorts", 
            "category": "mens new-in",
            "price": 55.00,
            "variant": "blue"
        }
    }
];   

}

(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=
'//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-MS3Q5D');


} + ')();';


var script = document.createElement('script');
script.textContent = actualCode;
(document.head||document.documentElement).appendChild(script);
script.parentNode.removeChild(script);

GTM Module - Debug Extension

Tag Name: GTM Module - Debug Extension

Tag Type: Custom HTML

Firing Rules: Event equals gtm.load

Blocking Rules: Debug Mode equals false
(requires debug macro)

Tag Code:

<script>
(function () {
    try {
        for(var f = document.getElementsByTagName('iframe'), x = f.length; x--;) if(f[x].src === 'about:blank')
            for(var r = f[x].contentDocument.querySelectorAll('tr[id$=brief]'), xx = r.length; xx--;) {
                var s=r[xx];
                s.setAttribute('title', 'click to show/hide details');
                s.style.cursor = 'pointer';
                s.onclick = function () {
                    var t=this.nextSibling;
                    t.style.display = t.style.display === 'none' ? 'table-row' : 'none';
                }
            }
    } catch(e) {}
})();
</script>

Auto Event Debugger

<script>

console.group('auto-event information for event action: ', {{event}});

console.groupCollapsed('auto-event element DOM object');
console.log('auto-event element DOM: %O', {{element}});
console.groupEnd();

console.groupCollapsed('auto-event element information');
console.log('auto-event element: ', {{element}});
console.log('auto-event element classes: ', {{element classes}});
if ({{element classes}}){
var noElmClass = document.getElementsByClassName({{element classes}}).length;
console.log('auto-event number of matching elements with above classes: ', noElmClass)
}
console.log('auto-event element id: ', {{element id}});
console.log('auto-event element target: ', {{element url}});
console.log('auto-event element name: ', {{element name}});
console.groupEnd();

console.groupCollapsed('auto-event element parent information');
console.log('auto-event element parent DOM: %O', {{element}}.parentElement);
console.dir({{element}}.parentElement);
console.log('auto-event element parent', {{element}}.parentElement);
console.log('auto-event element parent id', {{element}}.parentElement.id);
console.log('auto-event element parent classes', {{element}}.parentElement.className);
console.groupEnd();

console.groupCollapsed('auto-event url information');
console.log('url',{{url}});
console.log('url_hostname',{{url hostname}});
console.log('url_path',{{url path}});
console.groupEnd();

console.groupEnd();
</script>

jQuery Event

<script>
var elementSelector = '.btn-plrg-addtobasket.button.fn_sc_scAdd';

if( $(elementSelector).length === 0 ){

  console.log( 'missing' );

  dataLayer.push({
    'event' : 'event tracking error',
    'eventCategory' : 'event tracking error',
    'eventLabel' : elementSelector,
    'eventAction' : 'onclick element missing',
    'eventNonInteraction' : true,
  })

} else {

  $(elementSelector).on('click',function(){

    console.log( 'found' );
    console.log( $( this ) );

    dataLayer.push({
      'event' : 'event tracking',
      'eventCategory' : 'event category',
      'eventLabel' : 'event label',
      'eventAction' : 'event action',
      'eventNonInteraction' : true,
    })

  })

}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment