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