Skip to content
ANALYTICS

Finding pages missing Google Tag Manager snippet within Google Tag Manager

David Vallejo
Share

This time, we’ll be using Google Tag Manager itself, to find pages in our site that may be missing Google Tag Manager. Ok, it may sound strange, but was not able to find any other way to say it .

Basically we’re going to use a custom html tag, to detect is the previous page had loaded Google Tag Manager code.

To achive this we’ll be using a single Custom HTML tag ,a cookie and the onbeforeunload event.

The following flow chart will show you the logic that we’re going to follow to detect the pages that are missing the Google Tag Manager snipper for our site.

So we’ll create a new custom HTML tag (that will be fired for ALL pages default trigger), and then add the following code to it, remember to update the “hostName” variable value to your domain root:

<script>
  (function(){
    // Change this to your root domain name
  var hostName = 'thyngster.com';
    // On before Unload 
  window.onbeforeunload = function(e) {
  	expire = new Date();
  	expire.setTime(new Date()*1+10*1000);
  	document.cookie = "__ttt="+escape(1) + ";expires="+expire.toGMTString()+ ";domain=."+hostName+";path=/";
   	};  

    // If user's coming from elsewhere but our domain, exit.  
    if(location.hostname.split('.')[location.hostname.split('.').length -2].length==2)
      var rootDomainName = location.hostname.split('.').slice(-3).join('.');
    else
      var rootDomainName = location.hostname.split('.').slice(-2).join('.');
    if(document.referrer.indexOf(rootDomainName)==-1)
      {return;}


    function isCookiePresent(name) {
      match = document.cookie.match(new RegExp(name + '=([^;]+)'));
      if (match) return true; else return null;
    }

    if(!isCookiePresent('_ttt')){
      dataLayer.push({
        'event':'missingtag',
        'referrer': document.referrer
      });
      document.cookie = '__ttt=; expires=Thu, 2 Aug 2001 20:47:11 UTC; domain=.'+hostName+';path=/';
    }  
  })();  
</script>

Ok, that’s all! 

Now we could create a new Event tag that fires when the event equals to “missingtag” to send that data to Google Analytics.

If you’re struggling with some hits being sent from hardcoded tags, I suggest you to take a look to this great tip from @fastbloke  for being able to find them, and you could look to this other old post

If you’re sending the data to Google Analytics, remember to set the event to a nonInteractional hit!

Any feedback, comment or improvement will be really appreciated.