Reputation: 21
On my WordPress website I have a contact form built in Hubspot. I got the script of this form from Hubspot and past it in my contact page (https://stagezero.ai/contact/).
<script>
hbspt.forms.create({
region: "na1",
portalId: "20085053",
formId: "412d2c51-95f1-4a6c-b3f3-f71c5852ac98"
});
</script>
Whenever the form is submitted the user is redirected to our thank you page (https://stagezero.ai/thank-you/). So, whenever someone submit the form I want to extract the Emails of our users from the email field on our contact from. So basically, the goal is to get the emails stored as a variable so that it can be hashed and sent to google analytics. I have tried to do it by myself by writing and pasting this code in my contact page but unfortunately it did not work. Can some help me to achieve the goal which I have mentioned above? Thank you.
<script>
//code to get email values from contact form’s email field
var form = document.getElementById("hsForm_412d2c51-95f1-4a6c-b3f3-f71c5852ac98");
var email_field=document.getElementById("email-412d2c51-95f1-4a6c-b3f3-f71c5852ac98");
form.onsubmit = function(){
var email = email_field.value();
//code to send email values to Google Analytics
dataLayer.push({
'event':'form_submit',
'enhanced_conversion_data': {
"email": email // replace 'yourEmailVariable' with email variable //
}
});
};
</script>
Upvotes: 1
Views: 262
Reputation: 1508
@BNazaruk is correct in that it's an iframe and you wont be able to retrieve that data by using element selectors. However, Hubspot uses message passing for their internal tools so it's not documented, but through some extensive logging, I have found how to retrieve that email data.
<script>
//listen for the message event
window.addEventListener("message", function(event) {
//log the message data so you can see what hubspot is saying
console.log(event.data);
//detect the submission event
if(event.data.type === 'hsFormCallback' && event.data.eventName === "onFormSubmit") {
const email = event.data.data.submissionValues.email; //submissionValues will list out your form data so make sure to see what your exact key is for the email field.
//code to send email values to Google Analytics
dataLayer.push({
'event':'form_submit',
'enhanced_conversion_data': {
"email": email
}
});
}
});
</script>
Upvotes: 0