Jan 10, 2023

Firing Google Tag Manager events for Hubspot forms

Firing Google Tag Manager events for Hubspot forms

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>
 Copy
html

We’re *actually* here to help

We’re marketers who love spreadsheets, algorithms, code, and data. And we love helping other marketers with interesting challenges. Tackling the hard stuff together is what we like to do.

We don’t just show you the way—we’re in this with you too.

Background image of a red ball in a hole.