Search code examples
google-analyticsgoogle-tag-manageruniversal-analytics

Set custom page title in Google Tag Manager


I am working with a site where all of the title tags on the pages of their blog are set to automatically be the same. This causes some issues in Google Analytics with some custom reports we are using.

Since making changes to the CMS itself is off limits, what I would like to be able to do is to dynamically set the page title using a dataLayer variable based off of the blog post title.

Say for example I had the code:

<script type="text/javascript">    
  var links = document.getElementsByClassName("post")[0].getElementsByTagName("a");
  var title = links[0].innerHTML;
  dataLayer.push({'pageTitle': title})
</script>

How would I go about using that to rewrite the page title in Google Tag Manager?


Solution

  • Create a custom js macro (we'll call it pageTitle):

    function (){
      var links = document.getElementsByClassName("post")[0].getElementsByTagName("a"),
          title = links[0].innerHTML;
    
      return title;
    
    }
    

    Then in your Universal Analytics - Pageview Tag, pass in the macro {{pageTitle}} into the Document Title Field:

    enter image description here

    Might be better to use innerText/textContent for getting the text out of an anchor

    title = links[0].innerText || links[0].textContent;