Streaming live at 10am (PST)

How to get UTM parameters and send them inside Webflow Form

Minimal JS knowledge requires (Two copy-paste and Less than one minute).

Step 1/4:
Google/youtube What are UTM (Very useful for Marketing).
https://support.google.com/analytics/answer/1033863

Step 2/4:
Create a UTM link. Useful tool:
https://ga-dev-tools.appspot.com/campaign-url-builder/

In this example the UTM is:
?utm_source=facebook&utm_medium=post&utm_campaign=webflow
So the full link look like this:
www.my-site.com?utm_source=facebook&utm_medium=post&utm_campaign=webflow

Step 3/4
Copy-Paste Before body (Per page -or- entire website).

The code structure:

  1. Get URL parameters -
    code credit: https://www.sitepoint.com/get-url-parameters-with-javascript/
  2. Get webflow form elements by id and set the value to UTM param X.
<!-- Getting The URL Parameter - and set UTM inside webflow form - Siton -->
<script>
  function getAllUrlParams(url) {
    // get query string from url (optional) or window
    var queryString = url ? url.split('?')[1] : window.location.search.slice(1);
    // we'll store the parameters here
    var obj = {};
    // if query string exists
    if (queryString) {
      // stuff after # is not part of query string, so get rid of it
      queryString = queryString.split('#')[0];
      // split our query string into its component parts
      var arr = queryString.split('&');
      for (var i = 0; i < arr.length; i++) {
        // separate the keys and the values
        var a = arr[i].split('=');
        // set parameter name and value (use 'true' if empty)
        var paramName = a[0];
        var paramValue = typeof (a[1]) === 'undefined' ? true : a[1];
        // (optional) keep case consistent
        paramName = paramName.toLowerCase();
        if (typeof paramValue === 'string') paramValue = paramValue.toLowerCase();
        // if the paramName ends with square brackets, e.g. colors[] or colors[2]
        if (paramName.match(/\[(\d+)?\]$/)) {
          // create key if it doesn't exist
          var key = paramName.replace(/\[(\d+)?\]/, '');
          if (!obj[key]) obj[key] = [];
          // if it's an indexed array e.g. colors[2]
          if (paramName.match(/\[\d+\]$/)) {
            // get the index value and add the entry at the appropriate position
            var index = /\[(\d+)\]/.exec(paramName)[1];
            obj[key][index] = paramValue;
          } else {
            // otherwise add the value to the end of the array
            obj[key].push(paramValue);
          }
        } else {
          // we're dealing with a string
          if (!obj[paramName]) {
            // if it doesn't exist, create property
            obj[paramName] = paramValue;
          } else if (obj[paramName] && typeof obj[paramName] === 'string'){
            // if property does exist and it's a string, convert it to an array
            obj[paramName] = [obj[paramName]];
            obj[paramName].push(paramValue);
          } else {
            // otherwise add the property
            obj[paramName].push(paramValue);
          }
        }
      }
    }
    return obj;
  }
  /* get data object */
  var getAllUrlParams = getAllUrlParams();
  /* Check if the url with utm_parameters */
  let isEmpty = jQuery.isEmptyObject(getAllUrlParams); 
  if(!isEmpty){
    /* utm data */
    let utm_source_value = getAllUrlParams.utm_source;
    let utm_medium_value = getAllUrlParams.utm_medium;
    let utm_campaign_value = getAllUrlParams.utm_campaign;
    /* webflow form object (You should add embed code under webflow designer */
    var utm_source_form_elem = document.getElementById("utm_source");
    var utm_medium_form_elem = document.getElementById("utm_medium")
    var utm_campaign_form_elem = document.getElementById("utm_campaign");
    /* Check if elem exsist to avoid console errors  */
    if(utm_source_form_elem){
      utm_source_form_elem.value = utm_source_value;
    }
    if(utm_medium_form_elem){
      utm_medium_form_elem.value = utm_medium_value;
    }
    if(utm_campaign_form_elem){
      utm_campaign_form_elem.value = utm_campaign_value;
    }
  }
</script>


The code store the parameters inside getAllUrlParams object
image

If we want for example the utm_source we write:
getAllUrlParams.utm_source
image

Related: https://www.w3schools.com/js/js_json_objects.asp

Webflow side

Step 4/4

Add form and inside the form add embed html Copy - Paste (By code we are going to set the value of those feilds).

<input type="text" id="utm_source" name="utm_source"><br>
<input type="text" id="utm_medium" name="utm_medium"><br>
<input type="text" id="utm_campaign" name="utm_campaign"><br>

** Not mandatory: Its better to put the HTML embed before the submit button (Like this the form submission table will be more readable).

Publish

:slight_smile: The code fill up the empty feilds with UTM parameters:

Set type=“hidden”

If everything works as it should - set the fields type to hidden

I like to add an empty script (LIke this its more visual that I use some custom code inside this form).

validation

My code use if statements (Check if the fields exist. So its also ok to put this code under site setting (Will work fine also on pages without form -and/or- url without parameters.

1 Like

Cockies & UTM

Sometimes its useful to save utm params inside a cockie (To keep the UTM also if the user go from page X to Y).

Same steps as above (Only step 3 code is difference).
Save UTM-params inside Lead cookie.

I use this library. More options her:

** Default expires: Cookie is removed when the user closes the browser.


<!-- Getting The URL Parameter - and set UTM inside webflow form - Siton -->

<!-- https://github.com/js-cookie/js-cookie -->
<script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>

<script>
  function getAllUrlParams(url) {
    // get query string from url (optional) or window
    var queryString = url ? url.split('?')[1] : window.location.search.slice(1);
    // we'll store the parameters here
    var obj = {};
    // if query string exists
    if (queryString) {
      // stuff after # is not part of query string, so get rid of it
      queryString = queryString.split('#')[0];
      // split our query string into its component parts
      var arr = queryString.split('&');
      for (var i = 0; i < arr.length; i++) {
        // separate the keys and the values
        var a = arr[i].split('=');
        // set parameter name and value (use 'true' if empty)
        var paramName = a[0];
        var paramValue = typeof (a[1]) === 'undefined' ? true : a[1];
        // (optional) keep case consistent
        paramName = paramName.toLowerCase();
        if (typeof paramValue === 'string') paramValue = paramValue.toLowerCase();
        // if the paramName ends with square brackets, e.g. colors[] or colors[2]
        if (paramName.match(/\[(\d+)?\]$/)) {
          // create key if it doesn't exist
          var key = paramName.replace(/\[(\d+)?\]/, '');
          if (!obj[key]) obj[key] = [];
          // if it's an indexed array e.g. colors[2]
          if (paramName.match(/\[\d+\]$/)) {
            // get the index value and add the entry at the appropriate position
            var index = /\[(\d+)\]/.exec(paramName)[1];
            obj[key][index] = paramValue;
          } else {
            // otherwise add the value to the end of the array
            obj[key].push(paramValue);
          }
        } else {
          // we're dealing with a string
          if (!obj[paramName]) {
            // if it doesn't exist, create property
            obj[paramName] = paramValue;
          } else if (obj[paramName] && typeof obj[paramName] === 'string'){
            // if property does exist and it's a string, convert it to an array
            obj[paramName] = [obj[paramName]];
            obj[paramName].push(paramValue);
          } else {
            // otherwise add the property
            obj[paramName].push(paramValue);
          }
        }
      }
    }
    return obj;
  }

  /* Check if Lead Cookie already exist */
  var cookieExist = Cookies.get('Lead'); // => 'value'

  /* get data object */
  var getAllUrlParams = getAllUrlParams();
  /*Convert a JavaScript object into a string */
  var getAllUrlParamsJSON = JSON.stringify(getAllUrlParams) 
  /* set lead object for the cockies */
  const lead = {
    parameters: getAllUrlParams
  }

  /* Check if the url with utm_parameters */
  let isEmpty = jQuery.isEmptyObject(getAllUrlParams); 
  /* if the page with parameters create cockie */
  if(!cookieExist && !isEmpty){
    console.log("Create Cockie");
    var value = JSON.stringify(lead);
		/* 
		## Set Cookies ##
		expires: If omitted, the cookie becomes a session cookie (This example)
    */
    Cookies.set('Lead', lead, { });
  }/*end if*/
   
  var cookieCreated = Cookies.get('Lead'); // => 'value'
  
  if(cookieCreated && !isEmpty){
    /* utm data */
    let utm_source_value = lead.parameters.utm_source;
    let utm_medium_value = lead.parameters.utm_medium;
    let utm_campaign_value = lead.parameters.utm_campaign;
    /* webflow form object (You should add embed code under webflow designer */
    var utm_source_form_elem = document.getElementById("utm_source");
    var utm_medium_form_elem = document.getElementById("utm_medium")
    var utm_campaign_form_elem = document.getElementById("utm_campaign");
    /* Check if elem exsist to avoid console errors  */
    if(utm_source_form_elem && utm_source_value.length > 0){
      utm_source_form_elem.value = utm_source_value;
    }
    if(utm_medium_form_elem && utm_medium_value.length > 0){
      utm_medium_form_elem.value = utm_medium_value;
    }
    if(utm_campaign_form_elem && utm_campaign_value.length > 0){
      utm_campaign_form_elem.value = utm_campaign_value;
    }
  }
</script>
1 Like

Good evening thanks for this.

I am trying to save utm params inside a cookie (To keep the UTM also if the user go from page X to Y) . part of your suggestion but unfortunately it doesn’t work. Please see our sharable link below.

https://preview.webflow.com/preview/door31?utm_medium=preview_link&utm_source=designer&utm_content=door31&preview=7695d4f61408ac8c25d01f186103ebbe&pageId=5f4682f16241775f005551b4&mode=preview

I would be grateful if you could help us with this one.

Many thanks,
Stelios

Please add a live URL.

please see below the live URL

I update the code. Please copy-paste again and update if the problem solved.

HI Siton,

Thanks a lot for updating the code. i have copy-paste the code, before the body in all the pages but unfortunately, it doesn’t work. please see a screenshot attached

any other recommendations?

I really appreciate your help.

Many thanks,
SK

Clear cookies and than refresh the page.

Hi Siton,

Many thanks for your help with this. We cleared the cookies as you said, and it works. It shows the UTM values within the lead cookie.

Unfortunately now for some reason when we can’t seem to get the UTM data to come out of the cookies and into the contact form. Screenshot 2020-09-11 at 15.43.02

thanking you in advance,
Stelios

Copy-Paste the code again (lead instead of Lead in the code make minor error).
If now the code not working please write me in private (If the code working - like this comment).

https://test-c0d8d3.webflow.io/?utm_source=facebook&utm_medium=post&utm_campaign=webflow