I’m writing this post because I wanted to pass values into Hidden Fields that were in my Hubspot forms on Hubspot landing pages (not embedded) and I needed to use Google Tag Manager to do it.
I saw numerous posts across Hubspot on this issue involving cookies, embedded forms, jQuery, and more. I’ve done this same solution with lots of different forms: Marketo, HTML, etc. I knew it could be done.
In summary. I wanted to pass the current webpage that the form was being filled out on since we use global forms across our website and needed a field to capture the webpages so we could send people the correct content while also passing the field into other systems at scale.
How we accomplished this:
- Created Event listener in GTM.
- Setup Event Triggers from those events in GTM.
- Run a simple Javascript to update the field name of the hidden field with a value.
Step 1 - Create Event Listener in GTM for when Hubspot Forms are detected on the page
Event - Hubspot Form Ready
- Create a ‘Custom HTML’ tag, with the trigger in GTM, for All Pages.
- Add the following script into the HTML code block:
<script type="text/javascript">
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
});
}
});
</script>
Step 2 - Setup the Triggers in Google Tag Manager (and the optional Variables)
Setup the Event Trigger in GTM
- *Optional* Create a Variable, with variable type ‘Data Layer Variable’, the name of which is from the code above, ‘hs-form-guid’ and use Data Layer Version 2. (This is to be used if you have multiple forms and only want the event to trigger on specific forms).
- Create a Trigger, with trigger type ‘Custom Event’
- For the event name, use the same value as was used in the code above, ‘hubspot-form-ready’ or to whatever you changed that to.
- In the “This trigger fires on” set it to the Variable created above and use the form ID if you want it to trigger on a specific form. Otherwise you can run it however you want.
Step 3 - Create a Tag That Runs a Simple Javascript to Change the Value in the Hidden Field based on the Event firing.
Setup the Tag in GTM
- Create a ‘Custom HTML’ tag,.
- Set the Firing Triggers to include the Event Trigger you just created in Step 2.
- Add any exceptions you want.
- In the HTML code box, add the following script (replacing the field name with your own and the value with whatever you want the value to be):
<script>
document.querySelector("input[name='INSERT_FORM_FIELD']").value = {{Page URL}};
</script>
That’s it.
Notes:
- I’m not a developer… I know enough about GTM, Hubspot, and coding to get my hands dirty.
- Feel free to add ideas/modifications or better/cleaner/sleeker code if you want below.