Google Tag Manager events for Hubspot forms

Analytics with Ottimo

Introduction
Account setup
Collections
Why we built Ottimo
Release notes

Learning

Resources

Content Strategy Quickstart

Contact us

Firing Google Tag Manager events for Hubspot forms

Learn how to fire Google Tag Manager events for Hubspot forms using this helpful code snippet.

This code causes Hubspot to emit various form events that are helpful. It underreports the number of Hubspot Form Ready events on pages with multiple HS forms in certain cases, and probably should be improved to fix that.

<script type="text/javascript">
  window.addEventListener("message", function(event) {
    if(event.data.type === 'hsFormCallback' && event.data.eventName === 'onFormSubmitted') {
      window.dataLayer.push({
        'event': 'hubspot-form-success',
        'hs-form-guid': event.data.id
      });
      console.log("Submitted " + event.data.id);
    }
  });  

  if (document.querySelectorAll('.hs-form')[0] != undefined)
  {
      window.dataLayer.push({
        'event': 'hubspot-form-ready',
        'hs-form-guid': document.querySelectorAll('.hs-form')[0].getAttribute('data-form-id')
      });
      console.log("Ready " + document.querySelectorAll('.hs-form')[0].getAttribute('data-form-id'));
  }
  else
  {
  window.addEventListener("message", function(event) {
    if(event.data.type === 'hsFormCallback' && event.data.eventName === 'onFormReady') {
      window.dataLayer.push({
        'event': 'hubspot-form-ready',
        'hs-form-guid': event.data.id
      });
      console.log("Ready " + event.data.id);
    }
  });
  }
</script>
icon
You might find our newsletter helpful

Everything we have to say on SEO, content performance, and content analytics – in convenient email form.

super-embed:<div class="klaviyo-form-XshxEW"></div>

(Having doubts? Here's a recent issue.)