Embedded form tracking in GTM doesn't work in new form editor

JAalbers
Contributeur

When I use the new form editor (in beta), I discovered that the form tracking in GTM doesn't work. Form submits with 'old' embedded Hubspot forms still work. I used the code that's referred to all over the internet: 

 

<script type="text/javascript"> 
window.addEventListener("message", function(event) { 
  console.log(event.data);
  if(event.data.type === 'hsFormCallback' && event.data.eventName === 'onFormSubmitted') {
    
    window.dataLayer.push({ 
      'event': 'hubspot_form_success', 
      'hs-form-guid': event.data.id }); 
  } 
}); 
</script>

  

I've already checked the Hubspot documentation but can't find changes in how to track form submits with this new editor. Does anybody have a solution for this?

5 Solutions acceptées
JAalbers
Solution
Contributeur

Update: For people experiencing the same problem: I also reported this to the support team and I eventually received this response:

It has been very tricky to identify and test the new form editor to capture events in GTM. - Seems like at the moment this is not supported by the new editor, and we reached out to our engineering team, and we were not given any specific expectations if this is something that they plan to implement in the future. At least not during the BETA version of form submissions. In the meantime, the recommendation is to keep using the legacy form editor so you can continue keeping track and creating events for GTM. 

 

In short, the conversion tracking does not work with the new editor and will not work during the beta. I am very surprised that a company like Hubspot did not think about conversion tracking during development. The new editor works nicely, but I will certainly not use the new editor for this reason.

 

Please support my idea to integrate this functionality in the new editor. 

Voir la solution dans l'envoi d'origine

RobertColson
Solution
HubSpot Employee
HubSpot Employee

Hi all, HubSpot employee here!

I've researched internally, and our team suggests that the new form editor (i.e., Forms 2.0) uses a different event name. Kindly refer to the New Form Global Events doc to set up form events with GTM. For anything dev- or troubleshooting-related to this topic, it would be best to consult HubSpot Developer Support or the Developer Community.

 

Voir la solution dans l'envoi d'origine

0 Votes
JAalbers
Solution
Contributeur
Hi! I noticed two issues in your code:

- The correct event property is event.detail, not event.data. HubSpot uses the standard CustomEvent object, and the data is stored under .detail.
- You’re opening a block (with a curly bracket) directly after console.log(event.data); without a closing bracket — that’s a syntax error. Solution: remove the unnecessary curly bracket.

I’ve tested the new global events that @RobertColson  suggested — they work great!

You can use the following code in your Custom HTML tag and trigger it on DOM ready to ensure all relevant events are captured:
<script>
(function() {
function pushToDataLayer(eventName, event) {
window.dataLayer = window.dataLayer || [];

var formId = event.detail.formId;
var instanceId = event.detail.instanceId;

var data = {
event: eventName,
formId: formId,
instanceId: instanceId
};

dataLayer.push(data);
}

window.addEventListener('hs-form-event:on-submission:success', function(event) {
pushToDataLayer('form_submit_success', event);
});

window.addEventListener('hs-form-event:on-submission:failed', function(event) {
pushToDataLayer('form_submit_failed', event);
});

window.addEventListener('hs-form-event:on-interaction:navigate:next', function(event) {
pushToDataLayer('form_navigate_next', event);
});

window.addEventListener('hs-form-event:on-interaction:navigate:previous', function(event) {
pushToDataLayer('form_navigate_previous', event);
});
})();
</script>

 

Voir la solution dans l'envoi d'origine

0 Votes
FMaury
Solution
Participant

Hi! My bad I was OOO so I didn't catch the news on this matter...
If needed, I was working on a custom HTML GTM that listen the old and new Hubspot form submissions:

<script>
var eventName = "hubspot-form-success";
var includeFormData = true;

window.addEventListener("message", function(event) {
if (event.data && event.data.type === "hsFormCallback" &&
(event.data.eventName === "onFormSubmitted")) {
var formData = {
event: eventName + "-v3",
"hs-form-guid": event.data.id
};

if (includeFormData && event.data.data && event.data.data.submissionValues) {
for (var field in event.data.data.submissionValues) {
if (event.data.data.submissionValues.hasOwnProperty(field)) {
var cleanedField = field.replace(/[^\w]/g, "_");
var key = "hs-" + cleanedField;
formData[key] = event.data.data.submissionValues[field];
}
}
}

window.dataLayer = window.dataLayer || [];
window.dataLayer.push(formData);
}
});

window.addEventListener("hs-form-event:on-submission:success", function(event) {
if (typeof HubspotFormsV4 === "undefined") return;

var form = HubspotFormsV4.getFormFromEvent(event);
if (!form) return;

var formData = {
event: eventName + "-v4",
"hs-form-id": form.getFormId()
};

if (includeFormData) {
form.getFormFieldValues().then(function(values) {
if (values && values.length) {
for (var i = 0; i < values.length; i++) {
var field = values[i];
var cleanedName = field.name.replace(/[^\w]/g, "_");
var key = "hs-" + cleanedName;
formData[key] = field.value;
}
}
window.dataLayer.push(formData);
});
} else {
window.dataLayer.push(formData);
}
});
</script>

 

Voir la solution dans l'envoi d'origine

GParker97
Solution
Membre

Hello,

 

After hours of trial and error trying to find an equivalent to the legacy form solution, I've found that the below javascript works. It captures both the submission event, pushes the success event to the dataLayer, and captures the form ID as per the original code snippet, using the HubSpot recommended methods (as described on the HubSpot global forms page😞

 

<script type="text/javascript">
  window.addEventListener("hs-form-event:on-submission:success", function(event) {
      window.dataLayer.push({
        'event': 'hubspot_form_success',
        'hs-form-guid': HubSpotFormsV4.getFormFromEvent(event).getFormId(),
      });
  });
</script>

 

I've seen some other replies similar to this but not quite as simple or direct, so decided to post my solution as well.

 

Hope this helps!

 

Greg

Voir la solution dans l'envoi d'origine

27 Réponses 27
JPuybaraud
Participant

Just an update as I have experienced the same problem.

 

For people who would come after me, I used the code provided by FMaury (Thank you BTW) on this thread. But you'll still have to modify the trigger and everything as the event for form success is now hubspot-form-success-v4 and not hubspot-form-success anymore. If you are also looking for DLV such as email and phone for your Gads campaign, you will have to reconfigure your variables. Email is now under hs-0_1_email and phone under hs-0_1_mobilephone. If you want to get the form ID, it is not under hs-form-guid now but under hs-form-id.

 

Hope it helps.

 

Julien

FMaury
Participant

Thanks for the update! On my side it's still working on hubspot-form-success probably because my client didn't migrate on a new version yet.

I've made some udaptes too on my tracking code if this help I paste it right below (sorry comments are in french):

<script>
  (function() {
    //fonction servant à l'encodage SHA256 des données personnelles
    function sha256(message) {
      var msgBuffer = new TextEncoder().encode(message);
      return crypto.subtle.digest("SHA-256", msgBuffer)
        .then(function(hashBuffer) {
          var hashArray = Array.from(new Uint8Array(hashBuffer));
          var hashHex = hashArray.map(function(b) {
            return ("00" + b.toString(16)).slice(-2);
          }).join("");
          return hashHex;
        });
    }

    function pushToDataLayer(eventName, event) {
      window.dataLayer = window.dataLayer || [];

      var formId = event.detail.formId;
      var instanceId = event.detail.instanceId;
      
      //Listener du formulaire Hubspot
      var form = HubSpotFormsV4.getFormFromEvent(event);
      form.getFormFieldValues().then(function(fieldValues) {
        var data = {
          event: eventName,
          formId: formId,
          instanceId: instanceId
        };

        //Création du mapping pour les variables DLV existantes et ajout au dataLayer
        var hashPromises = [];
        var fieldMapping = {
          "lastname": "lastName",
          "firstname": "firstName",
          "mobilephone": "phoneNumber",
          "email": "emailAddress",
          "prm_zip": "postalCode",
          "prm_city": "city"
        };

        fieldValues.forEach(function(field) {
          var fieldName = field.name.replace("0-1/", "");
          var mappedFieldName = fieldMapping[fieldName] || fieldName;

          if (field.value !== "") {
            if (["lastname", "firstname", "mobilephone", "email"].indexOf(fieldName) !== -1) {
              hashPromises.push(sha256(field.value).then(function(hashedValue) {
                data[mappedFieldName] = hashedValue;
              }));
            } else {
              data[mappedFieldName] = field.value;
            }
          }
        });

        //Ajout du compteur de variable pour définir l'étape du "form_navigate_next"
        Promise.all(hashPromises).then(function() {
          if (eventName === 'form_navigate_next') {
            // Calcul du nombre de variables sans "event"
            var variableCount = 0;
            for (var key in data) {
              if (data.hasOwnProperty(key) && key !== 'event') {
                variableCount++;
              }
            }

            // Détermination du step
            if (variableCount <= 7) {
              data.formStep = 'step1';
            } else if (variableCount > 7 && variableCount <= 10) {
              data.formStep = 'step2';
            } else if (variableCount > 10 && variableCount <= 14) {
              data.formStep = 'step3';
            } else if (variableCount > 14) {
              data.formStep = 'step4';
            } else {
              data.formStep = 'unknown';
            }
          }

          dataLayer.push(data);
        });
      });
    }

    window.addEventListener('hs-form-event:on-submission:success', function(event) {
      pushToDataLayer('form_submit_success', event);
    });

    window.addEventListener('hs-form-event:on-submission:failed', function(event) {
      pushToDataLayer('form_submit_failed', event);
    });

    window.addEventListener('hs-form-event:on-interaction:navigate:next', function(event) {
      pushToDataLayer('form_navigate_next', event);
    });

    window.addEventListener('hs-form-event:on-interaction:navigate:previous', function(event) {
      pushToDataLayer('form_navigate_previous', event);
    });
  })();
</script>

 

You probably won't need everything as I custommed it regarding my own needs (especially on the steps counter which is not the best but works)

 

Have a great day

GParker97
Solution
Membre

Hello,

 

After hours of trial and error trying to find an equivalent to the legacy form solution, I've found that the below javascript works. It captures both the submission event, pushes the success event to the dataLayer, and captures the form ID as per the original code snippet, using the HubSpot recommended methods (as described on the HubSpot global forms page😞

 

<script type="text/javascript">
  window.addEventListener("hs-form-event:on-submission:success", function(event) {
      window.dataLayer.push({
        'event': 'hubspot_form_success',
        'hs-form-guid': HubSpotFormsV4.getFormFromEvent(event).getFormId(),
      });
  });
</script>

 

I've seen some other replies similar to this but not quite as simple or direct, so decided to post my solution as well.

 

Hope this helps!

 

Greg

BérangèreL
Gestionnaire de communauté
Gestionnaire de communauté

Hi @GParker97 and welcome to the HubSpot Community!

Thank you so much for sharing the solution, this will be really helpful for other Community Members who find this thread! ❤️

Have a wonderful weekend! 🌞
Bérangère





loop


Loop Marketing is a new four-stage approach that combines AI efficiency and human authenticity to drive growth.

Learn More




0 Votes
RobertColson
Solution
HubSpot Employee
HubSpot Employee

Hi all, HubSpot employee here!

I've researched internally, and our team suggests that the new form editor (i.e., Forms 2.0) uses a different event name. Kindly refer to the New Form Global Events doc to set up form events with GTM. For anything dev- or troubleshooting-related to this topic, it would be best to consult HubSpot Developer Support or the Developer Community.

 
0 Votes
G_Pereira
Membre

Hi ! 

I'm not an expert but I've done some tests with what you've provided and I couldn't get it to work on Google tag manager? Has anyone succeeded?

 

<script type="text/javascript"> 
window.addEventListener("hs-form-event:on-submission:success", function(event) { 
  console.log(event.data); {
    
    window.dataLayer.push({ 
      'event': 'hs-form-event:on-submission:success', 
      'hs-form-guid': event.data.id }); 
  } 
}); 
</script>

Have a nice day

 

0 Votes
JAalbers
Solution
Contributeur
Hi! I noticed two issues in your code:

- The correct event property is event.detail, not event.data. HubSpot uses the standard CustomEvent object, and the data is stored under .detail.
- You’re opening a block (with a curly bracket) directly after console.log(event.data); without a closing bracket — that’s a syntax error. Solution: remove the unnecessary curly bracket.

I’ve tested the new global events that @RobertColson  suggested — they work great!

You can use the following code in your Custom HTML tag and trigger it on DOM ready to ensure all relevant events are captured:
<script>
(function() {
function pushToDataLayer(eventName, event) {
window.dataLayer = window.dataLayer || [];

var formId = event.detail.formId;
var instanceId = event.detail.instanceId;

var data = {
event: eventName,
formId: formId,
instanceId: instanceId
};

dataLayer.push(data);
}

window.addEventListener('hs-form-event:on-submission:success', function(event) {
pushToDataLayer('form_submit_success', event);
});

window.addEventListener('hs-form-event:on-submission:failed', function(event) {
pushToDataLayer('form_submit_failed', event);
});

window.addEventListener('hs-form-event:on-interaction:navigate:next', function(event) {
pushToDataLayer('form_navigate_next', event);
});

window.addEventListener('hs-form-event:on-interaction:navigate:previous', function(event) {
pushToDataLayer('form_navigate_previous', event);
});
})();
</script>

 

0 Votes
FMaury
Participant

Hi! 

Thanks a lot for this code, I've modified it on my side to get all form fields values but you helped a lot 🙂

 

Just a question, did you manage to associate the "form_navigate_next" dataLayer event with the step ? I mean, if my form have 4 steps, I didn't figure out how to differenciate them... And I didn't find any help in the Hubspot API documentation

 

Thanks a lot!

0 Votes
AnnaGma
Membre

Hi @JAalbers ! 

Thanks a lot for the solution, it does work!

Do you know if it's also possible to track enhanced conversion data (send user's email to the data layer together with the success event)?


0 Votes
JAalbers
Contributeur

Hi @AnnaGma , 

 

By default, the hs-form-event:on-submission:success event does not expose the user's form input data (like email), so you can't directly grab the email address at that point. The data has already been sent to HubSpot, and it's no longer accessible via the DOM or the event object. You could listen for the user's input in the email field and when it has been filled, store it in sessionStorage. Then you can use it in you success-event. Below you can find a code example. Your input HTML field should have a name=“email” attribute for this to work.

 

How to Track the User's Email (for Enhanced Conversions)

  • Listen for the user's input in the email field
  • Capture the value when the user types it and store it in sessionStorage:
document.addEventListener('input', function(e) { if (e.target.name === 'email') { sessionStorage.setItem('hs_user_email', e.target.value); } });​
  • Retrieve the email when the form is successfully submitted
  • Modify your existing listener to include the stored email:
window.addEventListener('hs-form-event:on-submission:success', function(event) { var email = sessionStorage.getItem('hs_user_email'); window.dataLayer = window.dataLayer || []; dataLayer.push({ event: 'hubspot_form_success', hubspot_form_id: event.detail.formId, hubspot_form_instance_id: event.detail.instanceId, email: email }); });


This way, you can send the email address to the dataLayer alongside the success event, making it compatible with enhanced conversion setups (e.g. in Google Ads or GTM server-side tagging).

0 Votes
JAalbers
Contributeur

Additionally, I think it's best to only fire this code on pages that contain a HubSpot form. You can do that by creating a custom JavaScript variable with the following code:

function() {
  if ( document.querySelector('script[src*="hsforms.net"]') ) {
    return true;
  } else {
    return false;
  } 
}

Then, you can modify the trigger so that it only fires when this variable returns true.

0 Votes
FMaury
Participant

Hi!

I've been working with a colleague on a new version of the listener and everything seems to work so far!
We are making the last modifications but I can keep you updated when everything will be accessible so you can try on your side if you want?

JAalbers
Contributeur

Wow, great! Please share if you're ready.

0 Votes
FMaury
Solution
Participant

Hi! My bad I was OOO so I didn't catch the news on this matter...
If needed, I was working on a custom HTML GTM that listen the old and new Hubspot form submissions:

<script>
var eventName = "hubspot-form-success";
var includeFormData = true;

window.addEventListener("message", function(event) {
if (event.data && event.data.type === "hsFormCallback" &&
(event.data.eventName === "onFormSubmitted")) {
var formData = {
event: eventName + "-v3",
"hs-form-guid": event.data.id
};

if (includeFormData && event.data.data && event.data.data.submissionValues) {
for (var field in event.data.data.submissionValues) {
if (event.data.data.submissionValues.hasOwnProperty(field)) {
var cleanedField = field.replace(/[^\w]/g, "_");
var key = "hs-" + cleanedField;
formData[key] = event.data.data.submissionValues[field];
}
}
}

window.dataLayer = window.dataLayer || [];
window.dataLayer.push(formData);
}
});

window.addEventListener("hs-form-event:on-submission:success", function(event) {
if (typeof HubspotFormsV4 === "undefined") return;

var form = HubspotFormsV4.getFormFromEvent(event);
if (!form) return;

var formData = {
event: eventName + "-v4",
"hs-form-id": form.getFormId()
};

if (includeFormData) {
form.getFormFieldValues().then(function(values) {
if (values && values.length) {
for (var i = 0; i < values.length; i++) {
var field = values[i];
var cleanedName = field.name.replace(/[^\w]/g, "_");
var key = "hs-" + cleanedName;
formData[key] = field.value;
}
}
window.dataLayer.push(formData);
});
} else {
window.dataLayer.push(formData);
}
});
</script>

 

Chris_Bronc
Participant

I would love that. Please keep us updated! 

0 Votes
Cnadler
Contributeur | Partenaire solutions Gold
Contributeur | Partenaire solutions Gold

Are there any updates on this? 

MeikaB
Participant | Partenaire solutions Platinum
Participant | Partenaire solutions Platinum

Hey @JAalbers or @PamCotton 

We are looking to roll out these forms for a couple of clients, and I'm wondering if there have been any updates on tracking capabilities since the latest updates, please? 

0 Votes
JAalbers
Contributeur

Hi @MeikaB , I heard that the product team is actively working on this now. It should be rolled out by the end of the year.

0 Votes
SilasFindley
Participant

Hi @JAalbers, I just wanted to check to see if you have heard anything about the new form editor working with GTM now that it's December/almost the end of the year.

0 Votes
JAalbers
Contributeur

Unfortunately no! 

0 Votes