Inject UTM Parameter into Contact form using jQuery

Viewed 165

I am trying to inject a UTM parameter into our contact form. The contact form we are using is powered by FreshSales CRM and allows user to add hidden fields which should allow this to work.

The Parameters I want to pass are "Source, Medium and Campaign" and the UTM would look as follows:

?utm_source=google&utm_medium=cpc&utm_campaign=Conversion

I found the below code in a resource, does this need to be defined for each parameter or will this pull the entire UTM?

beforeSubmit: function()
{
console.log("Before submit hook triggered.");        
WebForm.$('<input>').attr({
           type: 'hidden',
           name: 'lead[custom_field][cf_utm_param]',
           value: getQueryVariable('utm_param')
         }).appendTo('.fs-webform-container form');
}

Any help would be very much appreciated. Thanks!

1 Answers

So I got this working to pass UTM values into the contact form. We had to create a Tag in Google Tag Manager to store the UTM value in a Cookie so if the user looks at multiple pages we can store this information.

Code below if anyone needs it:

 <script>
var WebFormEvent = {
  afterInstall: function(){
    console.log("After installation hook triggered. updated");        
  },
  beforeSubmit: function(){
  function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
      var c = ca[i];
      while (c.charAt(0) == ' ') {
        c = c.substring(1);
      }
      if (c.indexOf(name) == 0) {
        return c.substring(name.length, c.length);
      }
    }
    return "";
  }

  const gtmCompaignUrl = new URL(getCookie('__gtm_campaign_url'));

  function getQueryVariable(variable) {
    var query = gtmCompaignUrl.search.substring(1) || "";
    var vars = query.split('&');
    for (var i = 0; i < vars.length; i++) {
      var pair = vars[i].split('=');
      if (decodeURIComponent(pair[0]) == variable) {
        return decodeURIComponent(pair[1]);
      }
    }
  }
  const values = {
    source: getQueryVariable('utm_source'),
    medium: getQueryVariable('utm_medium'),
    campaign: getQueryVariable('utm_campaign'),
  }

  console.log("Before submit hook triggered.", values);  
  WebForm
    .$('<input>')
    .attr({
      type: 'hidden',
      name: 'lead[custom_field][cf_utm_source]',
      value: values.source,
    })
    .appendTo('.fs-webform-container form');

  WebForm
    .$('<input>')
    .attr({
      type: 'hidden',
      name: 'lead[custom_field][cf_utm_medium]',
      value: values.medium,
    })
    .appendTo('.fs-webform-container form');

  WebForm
    .$('<input>')
    .attr({
      type: 'hidden',
      name: 'lead[custom_field][cf_utm_campaign]',
      value: values.campaign,
    })
    .appendTo('.fs-webform-container form');
  }
}
</script>
Related