Capture Email and Phone from a HubSpot Form That Changes After First Submission

Posted by: Ed Hungerford Date Posted: December 18, 2024
Back to Case Studies

Issue

Like Pardot forms, some HubSpot forms will store user data in the browser after the first submission, causing a new, shorter form to appear in its place on subsequent visits. Sourcemap’s Request a Demo form exhibits this same behavior, and while capturing email/phone data is trivial on the first submit (simply send the captured email and phone along with the form ID in the usual event listener), the email and phone fields disappear from the form the second time around.

Solution

When the email and phone data are sent in the first submission, they are stored in a session storage variable called “kl:traits” that we can pull from afterwards. In order to make sure we get the right variable every time, the user-provided data fields are lookup tables that do the following:

  1. If the email and phone fields are present on the form, just capture them as a dataLayer variable from the HubSpot event listener.
  2. If the email and phone fields are not present, make the dataLayer variables equal to “false.”
  3. If the dataLayer variables are equal to “false”, instead pull the values from session storage.

Achievement

Captured email and phone data for enhanced conversions on a HubSpot form that truncated itself after the first submission.

Snippet/Screenshot/Link

============ cHTML HubSpot listener ============

<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,
'hsEmail': event.data.data.submissionValues.email || "false",
'hsPhone': event.data.data.submissionValues.phone || "false"
}); 
} 
}); 
</script>
============ Custom JS to get session storage ============ 
function(){
if(!localStorage["kl:traits"]) return "false";
return JSON.parse(localStorage["kl:traits"]).phone;
}