I have a HubSpot form in my website where I am trying to get leads from the users. As the webpage is also connected to an active Google Ads account, I need to send the input field which holds the email to Google Tag Manager. To do so first of all, I wrote the following code in my website's <head>
section:
<head>
...
<script>
window.dataLayer = window.dataLayer || [];
</script>
...
</head>
Then, I created a Data Layer variable in Google Tag Manager dashboard which looks like below:
Finally, in my HubSpot form, I added onFormSubmitted
function which looks like below to push the variable and its value (the user's email) to Tag Manager:
<script charset="utf-8" type="text/javascript"
src="//js-eu1.hsforms.net/forms/shell.js"></script>
<script>
hbspt.forms.create({
region: "eu1",
portalId: "xxxxxxxx",
formId: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
onFormSubmitted: function ($form) {
dataLayer.push({ 'var': String($form.find('input[name="email"]').val()) });
}
});
</script>
After adding these pieces of codes, when I check the Google Ads Submit Lead Form Conversion, I still can't see the value.
How can I fix this?
After searching a lot and some interviews with Google Ads support team, I solved the issue using sessionStorage
and JavaScript. like below:
<!-- index.html -->
<script>
hbspt.forms.create({
region: "eu1",
portalId: "xxxxxxxx",
formId: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
onFormSubmitted: function($form) {
sessionStorage.setItem("entered_email", $form.find('input[name="email"]').val());
}
});
</script>
As the HubSpot form is redirected to a "Thank You" page after submission, inside this page:
<!-- thanks.html -->
<span id="email_entered"></span>
<script>
$("#email_entered").text(sessionStorage.getItem('entered_email'));
</script>
For more details you can refer to How to recover a value from localStorage in JavaScript on mobile devices?