I have an external website where we have using Hubspot forms embed via an iframe to collect details. There are multiple forms so I am trying to write one script for all the forms.
I am trying to attach the Google Client ID as a hidden field with each submission. Using the Custom HTML tag on Google Tag Manager I have added following script to the page. But none of the 3 callbacks are able to fill the value for the hidden input field.
- onFormReady: callback is not even firing
- onFormSubmit: callback is getting fired but it did NOT attach the value to input field
- onBeforeFormSubmit: callback is getting fired but it did NOT attach the value to input field
Can you please suggest the right approach to achieve this? Or if something is wrong with the current code?
<script>
(function() {
window.addEventListener('message', function (event) {
ga_client_id = '{{Return Client ID}}';
if (event.data.type === 'hsFormCallback' && event.data.eventName === 'onFormReady') {
console.log(event.data);
console.log("onFormReady");
document.getElementById("hs-form-iframe-0").contentDocument.querySelector('input[name="ga_client_id"]').value = ga_client_id;
}
if (event.data.type === 'hsFormCallback' && event.data.eventName === 'onFormSubmit') {
console.log(event.data);
console.log("onFormSubmit");
document.getElementById("hs-form-iframe-0").contentDocument.querySelector('input[name="ga_client_id"]').value = ga_client_id;
}
if (event.data.type === 'hsFormCallback' && event.data.eventName === 'onBeforeFormSubmit') {
console.log(event.data);
console.log("onBeforeFormSubmit");
document.getElementById("hs-form-iframe-0").contentDocument.querySelector('input[name="ga_client_id"]').value = ga_client_id;
}
});
})();
</script>

