google-tag-managerfacebook-chatbot

Invalid HTML, CSS, or JavaScript error in Google Tag Manager with FB Bot


I'm trying to put the following Facebook bot code into Google Tag Manager but am getting the "Invalid HTML, CSS, or JavaScript found in template." error. Any idea why?

<!-- Load Facebook SDK for JavaScript -->
<div id="fb-root"></div>
<script>(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = 'https://connect.facebook.net/en_US/sdk/xfbml.customerchat.js#xfbml=1&version=v2.12&autoLogAppEvents=1';
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>

<!-- Your customer chat code -->
<div class="fb-customerchat"
  attribution="setup_tool"
  page_id="1393263590925062">
</div>

Solution

  • GTM does not allow non-standard HTML attributes. Hence "attribution" and "page_id" in the HTML element will cause GTM throw error.

    You can use Javascript to generate the chat code. Tested and it works.

    <script>
      (function() {
        var el = document.createElement('div');
        el.className = 'fb-customerchat';
        el.setAttribute('page_id', '{{Constant - Facebook Page ID}}');
        el.setAttribute('attribution', 'setup_tool');
        document.body.appendChild(el);
      })();
    </script>
    

    p/s: You can replace the variable {{Constant - Facebook Page ID}} with the page ID. It is best practice to use user-defined constant variables, read here.