Hooking Conversion Path into HubSpot forms is crazy easy

A long time ago, my friend Joe Fusaro (now at DataChef) and I wrote the still-solid Conversion Path JS attribution library. Conversion Path takes the usually lightweight “UTM-to-cookie” concept and injects it with some kind of superdrug. It has an insane amount of configurability.

When we wrote it, we were adamant about our JS API hooking into any form, including a plain vanilla HTML <form>. (It integrates with Marketo forms automatically.)

Few — or maybe zero — users explored Conversion Path Custom Events back in the day, but recently someone switched to Hubspot and wanted to stick with the script. And it was mind-blowingly simple, thanks to the work put in back then:

<script type="application/json" id="CP_TouchHistoryOptions">
{
  "events": {
    "model" : "customEvents",
    "injectHiddenFields" : false
  }
}
</script>
<script src="https://du4pg90j806ok.cloudfront.net/js/touch-history/dist/conversionpath-0.4.3.min.js"></script>
<script>
  window.addEventListener("message", function(e){
    if( e.origin === document.location.origin && e.data.type === "hsFormCallback" ) {
      let formEl = document.querySelector(`form.hsForm_${e.data.id}`);

      if( e.data.eventName === "onFormReady" ) {
        let ce = new Event("RC_TouchHistoryFormReady", { bubbles: true });      
        formEl.dispatchEvent(ce);
      } else if ( e.data.eventName === "onBeforeFormSubmit" ) {
        let ce = new Event("RC_TouchHistoryRecordable", { bubbles: true });
        formEl.dispatchEvent(ce);
      }
    }
  });
</script>

Enjoy!