Skip to content

Instantly share code, notes, and snippets.

@joziahg
Last active May 15, 2024 00:36
Show Gist options
  • Save joziahg/b895c7791306802f43978932e9e38fd7 to your computer and use it in GitHub Desktop.
Save joziahg/b895c7791306802f43978932e9e38fd7 to your computer and use it in GitHub Desktop.
Javascript code to intercept hubspot forms on drag and drop builder websites
<!-- Header Code -->
<script charset="utf-8" type="text/javascript" src="//js.hsforms.net/forms/shell.js"></script>
<!-- Footer Code -->
<!-- Minified use this in production -->
<script>
$('form[action^="https://api.hsforms.com"]').each((function(e){$(this).find("input[type=checkbox]").val("true"),$(this).submit((function(e){e.preventDefault();const n=[...new FormData(e.target).entries()].map((e=>({name:e[0],value:e[1]}))),t=n.find((e=>"goToWebinarWebinarKey"===e.name))?.value,i=n.find((e=>"sfdcCampaignId"===e.name))?.value,o=document.cookie.replace(/(?:(?:^|.*;\s*)hubspotutk\s*\=\s*([^;]*).*$)|^.*$/,"$1")||void 0;console.log(o);const s=$(this).find("[id*='gdpr-processing-prompt']"),a=n.filter((e=>e.name.includes("LEGAL_CONSENT"))).map((e=>{const n=$(`#${e.name.replace(/(:|\.|\[|\]|,|=|@)/g,"\\$1")}`)[0],t=$("span[for='"+$(n).attr("id").replace(/(:|\.|\[|\]|,|=|@)/g,"\\$1")+"']");return{value:n.checked,text:t.text(),subscriptionTypeId:parseInt(e.name.split("LEGAL_CONSENT.subscription_type_")[1])}})),r=["cc-num","cc-number","gdpr","LEGAL_CONSENT","goToWebinarWebinarKey","sfdcCampaignId"],c={fields:n.filter((e=>!r.find((n=>e.name.includes(n))))),context:{pageUri:window.location.href,pageName:document.title,sfdcCampaignId:i,goToWebinarKey:t,hutk:o},...s?{legalConsentOptions:{consent:{...s?{consentToProcess:!0,text:s.text()}:{},...a?{communications:a}:{}}}}:{}},l=JSON.stringify(c);$.ajax({url:e.target.action,method:"POST",data:l,contentType:"application/json",success:function(n){if(n)if(n.inlineMessage){const t=$(e.target).parent();t.children("form").css("display","none"),t.children(".w-form-done").css("display","block").html(n.inlineMessage)}else n.redirectUri&&(window.location.href=n.redirectUri);else console.log("response but no inlineMessage or redirectUri")},error:function(){console.log("error on the form submitting"),$(e.target).css("display","none").siblings(".w-form-fail").css("display","block")}})}))}));
</script>
<!-- Documented, dont use this in production. Copy and paste into a minifier to get the minified version above -->
<script type="text/javascript">
$('form[action^="https://api.hsforms.com"]').each(function (i) { // intercept forms whos action goes to hubspot
$(this).find("input[type=checkbox]").val("true")
$(this).submit(function (e) { // when the form submits
e.preventDefault() //stop the form from submitting to webflow
const formData = new FormData(e.target) // get the form data
const parsedFormData = [...formData.entries()].map(dataObject => ({ // convert data to array
name: dataObject[0], // make sure the name of the input is the same as the hubspot input name
value: dataObject[1] // the value of the input
}))
const goToWebinarWebinarKey = parsedFormData.find(input => input.name === 'goToWebinarWebinarKey')?.value // looks for an input with the name goToWebinarWebinarKey
const sfdcCampaignId = parsedFormData.find(input => input.name === 'sfdcCampaignId')?.value// looks for an input with the name sfdcCampaignId
const hutk = document.cookie.replace(/(?:(?:^|.*;\s*)hubspotutk\s*\=\s*([^;]*).*$)|^.*$/, "$1") || undefined // looks for an input with the name hutk, the hubspot user token
console.log(hutk)
const processingPrompt = $(this).find("[id*='gdpr-processing-prompt']")// looks for an element with the id gdpr-processing-prompt
const communicationConsent = parsedFormData.filter(item => item.name.includes('LEGAL_CONSENT')).map(item => { // finds LEGAL_CONSENT options and stores them
const element = $(`#${item.name.replace(/(:|\.|\[|\]|,|=|@)/g, "\\$1")}`)[0] // checks if they've checked the checkbox to consent
const label = $("span[for='" + $(element).attr('id').replace(/(:|\.|\[|\]|,|=|@)/g, "\\$1") + "']") // gets the label of the checkbox
return {
value: element.checked,
text: label.text(),
subscriptionTypeId: parseInt(item.name.split("LEGAL_CONSENT.subscription_type_")[1]) // the subscription the user is consenting to
}
})
const ignoredFields = ["cc-num", "cc-number", "gdpr", "LEGAL_CONSENT", "goToWebinarWebinarKey", "sfdcCampaignId"]
const data = { // the data we send to hubspot
"fields": parsedFormData.filter(item => !ignoredFields.find(ignoredField => item.name.includes(ignoredField))), // set the form data but ignore certain fields
"context": {
"pageUri": window.location.href, // log the current url
"pageName": document.title, // log the pages title
"sfdcCampaignId": sfdcCampaignId, // salesforce campaign id
"goToWebinarKey": goToWebinarWebinarKey, // go to meeting key
"hutk": hutk, // hubspot user token
},
...(!processingPrompt) ? {}
: {
"legalConsentOptions": {
"consent": {
...(!processingPrompt) ? {}
: {
"consentToProcess": true,
"text": processingPrompt.text(),
},
...(!communicationConsent) ? {}
: {
"communications": communicationConsent
}
}
}
}
}
const final_data = JSON.stringify(data) // turn that javascript object into a json string
$.ajax({
url: e.target.action,
method: "POST",
data: final_data,
contentType: "application/json",
success: function (response) {
if (response) {
if (response.inlineMessage) {
const parent = $(e.target).parent()
parent.children("form").css("display", "none") // hide form
parent.children(".w-form-done").css("display", "block").html(response.inlineMessage) // replace .w-form-done with your own form done section
} else if (response.redirectUri) {
window.location.href = response.redirectUri
}
} else {
console.log('response but no inlineMessage or redirectUri')
}
},
error: function () {
console.log("error on the form submitting")
$(e.target).css('display', 'none').siblings('.w-form-fail').css('display', 'block') // replace .w-form-fail with your own form done section
}
})
})
})
</script>
@pbrittliff
Copy link

Hi @joziahg awesome job. Loaded up followed video instructions and bam worked like a treat. However as soon as I wanted to add a company field (ie. COMPANY.xxx) it through a 400 error. Little bit of digging showed that the COMPANY.xx no longer seems to work and you need to use 0-2/. Damn can't add / in Webflow as its automatically replaced with a hyphen.

Debosmit Ray on your Youtube vid commented that he added some footer code to modify the array
const parsedFormData=unprocessedParsedFormData.map(a=>"COMPANY.name"===a.name?{...a,name:"0-2/name"}:a);

When I go to add it and minify the code it throws an error. Not sure why. Any chance you can update the video/code to address this change?

@Fulger09
Copy link

Thanks, author.

Unfortunately, this doesn't work for me for the Webflow site. With and without hidden input - it doesn't send user cookie to HubSpot and creates separate contacts.

Is there any updates of the code up to date?

Appreciate

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment