Knowledge |

Tracking HubSpot forms with Google Tag Manager

When a form has been successfully submitted to HubSpot, HubSpot propagates an event that we can listen to and use to trigger marketing tags within Google Tag Manager. Below we create a Custom HTML Tag that listens for a form success, trigger a dataLayer event which can then be used to trigger a marketing tag to push this data into Google Analytics.

Note: This method of tracking forms has been working since the 1st of June ’18, however, this is an undocumented event that may disappear at some point in the future. So, in the meantime, enjoy!

First, create a Custom HTML Tag, name it something appropriate (SCRIPT – HubSpot Form Listener or similar) and add an “All Pages” trigger to the page with the script below as the tag HTML:

Here’s the code:

<script type="text/javascript">
window.addEventListener("message", function(e){
    if (!/(hubspot|hsforms)\.com/i.test(e.origin))
        return;
   
    if (e.data.accepted)
      window.dataLayer.push({
        'event': 'hubspot-form-success',
        'hs-form-guid': e.data.formGuid
      });
});
</script>

Next, create a variable to read the hs-form-guid property (at this time, the HubSpot event does not expose the form name):

Create a new trigger for the Data Layer event triggered by the event listener:

Finally, create a new tag that uses the new trigger and HubSpot Form GUID, to send this data to Google Analytics:

Bonus Tip: If you store the HubSpot Form GUID as a hit-scoped custom dimension and add a further hit-scoped dimension called “Form Name” to Google Analytics, you can use Google Analytics’ data import functionality to enrich your data with friendly HubSpot form names instead of GUIDs within your custom reports.