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

Turn content into a growth engine.

Content is more than traffic. We connect strategy, messaging, and measurement so content directly contributes to pipeline, conversions, and expansion—and you can prove it.

Background image of a red ball in a hole.