How to Track HubSpot Forms in GA4 and GTM


Mastering HubSpot form tracking in GA4 ensures you never miss a lead conversion due to iFrame or JavaScript limitations.

The Challenge: Why HubSpot Forms Are "Invisible"

HubSpot forms often load via iFrames or dynamic JavaScript. Standard GTM "Form Submission" triggers can't see these events because they don't bubble up to the main window. To fix this, we need a custom listener that communicates between the HubSpot form and your Data Layer.

Method 1: The GTM JavaScript Listener (Best Practice)

This method captures the onFormSubmitted event directly from HubSpot's postMessage API. It is the most reliable way to track conversions without relying on thank-you page redirects.

1. Create the Custom HTML Tag

In GTM, create a Custom HTML Tag triggered on All Pages:

JavaScript
<script>
    window.addEventListener("message", function(event) {
        if(event.data.type === 'hsFormCallback' && event.data.eventName === 'onFormSubmitted') {
            window.dataLayer = window.dataLayer || [];
            window.dataLayer.push({
                'event': 'hubspot_form_success',
                'hs_form_id': event.data.id
            });
        }
    });
</script>

2. Configure the Trigger and GA4 Tag

  • Trigger: Create a Custom Event trigger named hubspot_form_success.
  • GA4 Tag: Create a GA4 Event tag with the event name generate_lead and fire it using the trigger above.

Method 2: Native HubSpot Embed Callback

If you have direct access to the website code and don't want to use GTM for the listener, you can add the tracking event directly into the HubSpot embed script:

JavaScript
hbspt.forms.create({
    region: "na1",
    portalId: "0000000",
    formId: "your-form-guid",
    onFormSubmitted: function($form) {
        // Direct GA4 Event
        gtag('event', 'generate_lead', {
            'form_id': 'contact_form'
        });
    }
});

Advanced: Tracking Validation Errors

Tracking when users fail to submit a form is crucial for CRO. Add this snippet to your GTM listener to capture validation errors:

JavaScript
if(event.data.eventName === 'onFormFailedValidation') {
    window.dataLayer.push({
        'event': 'hubspot_form_error',
        'hs_form_id': event.data.id
    });
}

Summary

Using a GTM listener is the cleanest way to track HubSpot forms in GA4. It prevents duplicate data, works with iFrames, and provides granular insights into user behavior. Always test your setup using the GTM Preview mode and GA4 DebugView before going live.

Report an issue

Stay in touch

Notes on Web Development

New articles on web development, accessibility, and technical SEO.

Occasional deep dives into platform-specific topics like HubSpot CMS, based on real-world problems and solutions.