Hi, I am using GTM and GA4 on my website to gather analytics data. I have embedded a hubspot form that i created a hidden block on labeled ‘GA Client ID’ (internal name is ga_client_id) in hopes that a GTM/javascript setup will be able to inject the client id data into that block so when someone submits the form their client id is carried over into hubspot too. currently i am using a custom html tag in GTM that fires after my config tag triggered on all pages. The tag is firing fine but the data is not being injected and im getting a 403 error on the form too. Here is the script:
<script>
function injectGAClientId() {
if (typeof gtag !== ‘function’) {
// Retry after 300ms if gtag isn’t ready
setTimeout(injectGAClientId, 300);
return;
}
gtag(‘get’, ‘G-KDPBR8EQT4’, ‘client_id’, function(clientId) {
if (!clientId) {
setTimeout(injectGAClientId, 300);
return;
}
var attempts = 0;
var interval = setInterval(function() {
var inputs = document.querySelectorAll(‘input[name$=“ga_client_id”]’);
if (inputs.length > 0) {
inputs.forEach(function(input) {
input.value = clientId;
});
clearInterval(interval);
console.log(‘Injected GA Client ID:’, clientId);
}
attempts++;
if (attempts > 20) clearInterval(interval);
}, 300);
});
}
window.addEventListener(‘load’, injectGAClientId);
</script>
my embedded code on my websites elementor html block is:
<script charset=“utf-8” type=“text/javascript” src=“//js-na2.hsforms.net/forms/v2.js”></script>
<script>
function getGA4ClientId() {
const cookieValue = document.cookie.split(‘; ‘).find(row => row.startsWith(’_ga=’));
return cookieValue ? cookieValue.split(‘=’)[1].split(‘.’).slice(-2).join(‘.’) : ‘not_set’;
}
hbspt.forms.create({
region: “na2”,
portalId: “243078151”,
formId: “29239f66-0317-4f23-9fb5-879021dd5bca”,
target: “#hubspot-form-container”,
onFormReady: function(form) {
var clientId = getGA4ClientId();
var hiddenField = document.querySelector(‘input[name=“ga_client_id”]’);
if (hiddenField) {
hiddenField.value = clientId;
console.log(“Set GA client ID:”, clientId);
}
}
});
</script>
<div id=“hubspot-form-container”></div>
I’ve looked high and low for a solution and this forum is my last resort, hoping someone can help, ty.