How to get UTM parameters and send them inside Webflow Form

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

Demo: utm without cockle

Step 1/4:
Google/youtube What are UTM (Very useful for Marketing).

Step 2/4:
Create a UTM link. Useful tool:

In this example the UTM is:
?utm_source=facebook&utm_medium=post&utm_campaign=webflow
“Full” link:
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 -
  2. Get webflow form elements by jquery class selector and set the value to this UTM param X.
<script>
  var queryString = window.location.search;
  console.log(queryString);
  // ?utm_source=facebook&utm_medium=post&utm_campaign=webflow
  var URLSearchParams_wb = new URLSearchParams(queryString);

  const utmParameters = [
    "utm_source", 
    "utm_medium", 
    "utm_campaign"
  ];

  for (const utm_element of utmParameters) {
    /* if utm_source exist */
    $( "form" ).each(function( index ) {
      if(URLSearchParams_wb.has(utm_element)){
        console.log(utm_element + "is exist");
        /* get UTM value of this utm param */
        var value = URLSearchParams_wb.get(utm_element)
        /* change form hidden feild to this utm url value */
        $( this ).find("."+utm_element).val(value);
      }

    })
  }/* end for loop */
</script>

Example:
URLSearchParams.get("utm_source")
return: “facebook” (For the url example)

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" class="utm_source" placeholder="utm_source" name="utm_source">
<input type="text" class="utm_medium" placeholder="utm_medium" name="utm_medium">
<input type="text" class="utm_campaign" placeholder="utm_campaign" name="utm_campaign">

** 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 fields with UTM parameters

**works also for more than one form on a page

Set type=“hidden”

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

I like to add an empty script (LIke this it’s more visual there are hidden fields inside this form).

validation

I use if statements (Check if the fields exist. So it’s also ok to put this code under site setting (Will work fine also on pages without form -and/or- URL without parameters -or- some parameters).

3 Likes

Cockies & UTM

Demo: utm cockie

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 different).

Embed inside the form:

<input type="text" class="utm_source" placeholder="utm_source" name="utm_source">
<input type="text" class="utm_medium" placeholder="utm_medium" name="utm_medium">
<input type="text" class="utm_campaign" placeholder="utm_campaign" name="utm_campaign">

Save UTM-params inside Lead cookie.

I use this library. More options her:

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

Copy-Paste before body

(Code update on: 13/12/2021)


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

<!-- ezra siton code -->
<script>
  const my_utmParameters = [
    "utm_source", 
    "utm_medium", 
    "utm_campaign"
  ];

  function getAllUrlParams(url) {
    let obj = Object.fromEntries(new URLSearchParams(location.search));
    return obj;
  }
  /* Check if Lead Cookie already exist */
  var cookieExist = Cookies.get('Lead'); // => if false return undefined
  /* get URL params object */
  var getAllUrlParams = getAllUrlParams(); // return object
  /*Convert a JavaScript object into a string */
  var getAllUrlParamsJSON = JSON.stringify(getAllUrlParams);
  /* Check if the url with utm_parameters */
  let isEmpty = jQuery.isEmptyObject(getAllUrlParams); // return true/false

  /* Case 1 - if the page with parameters & no cockie exsist */
  if(!isEmpty && cookieExist === undefined){
    /* Set lead object for the cockies */
    console.log("Case 1 - parameters & no cockie exsist => Create Cockie");
    /* 
		## Set Cookies ##
		expires: If omitted, the cookie becomes a session cookie (This example)
    */
    createLead();
    setUTMformValues();
  }/*end if*/

  let compare = is_this_utm_equal_to_cockie_utm_values();

  if(!isEmpty && cookieExist !== undefined){
    /* it this utm params diff from current lead values create new lead*/
    if(!compare){
      /* Case 3 - cockie already exsist but with diff values Vs url utm parmas
			(remove current Lead and generate new one) 
      */
      console.log("Case 3 - lead Exist, but with diff parames");
      Cookies.remove('Lead');
      createLead();
      setUTMformValues();
    }else{
      console.log("Case 2 - lead exsist with this params");
      setUTMformValues();
    }
  }

  /* Case 4 - cookie Exist  but page without any utm param */
  if(isEmpty && cookieExist !== undefined){
    console.log("Case 4 - cookie Exist  but page without any utm param");
    setUTMformValues();
  }

  function createLead(){
    var lead = {
      parameters: getAllUrlParams
    };
    /* if you want to add 2 days expires for example: 
   Cookies.set('Lead', 'lead', { expires: 2}) 
   */
    Cookies.set('Lead', lead, { });
  }

  /* check if this utm url equal to the current values of cockie lead */
  function is_this_utm_equal_to_cockie_utm_values(){
    for (const this_utm_element of my_utmParameters) {
      /* if utm_source exist */
      let value_exsist = JSON.parse(cookieExist).parameters[this_utm_element] == getAllUrlParams[this_utm_element];
      //console.log(`${value_exsist} - ${JSON.parse(cookieExist).parameters[this_utm_element]} compare to: ${getAllUrlParams[this_utm_element]}`);
      if(value_exsist == false){
        return false;
      }
    }/* end for loop */
    return true;
  }

  function setUTMformValues(){  
    /* webflow form object (Add embed code under webflow designer inside FORM */
    /*
		<input type="text" class="utm_source" placeholder="utm_source" name="utm_source">
<input type="text" class="utm_medium" placeholder="utm_medium" name="utm_medium">
<input type="text" class="utm_campaign" placeholder="utm_campaign" name="utm_campaign">
	*/
    /* the value if the param is empty */
    const empty_param_case = "null";
    /* set feilds */
    for (const this_utm_element of my_utmParameters) {
      /* if utm_source exist */
      set_utm_feild(this_utm_element);
    }/* end for loop */

    /* inner function */
    function set_utm_feild(utm_type){
      let utm_value = JSON.parse(Cookies.get('Lead')).parameters[utm_type];
      let utm_nodes = document.getElementsByClassName(utm_type);
      /* change all utm form feilds */
      if(utm_nodes.length > 0){
        for(var i = 0; i < utm_nodes.length; i++)
        {
          if(!!utm_value && utm_value !== undefined){
            utm_nodes[i].value = utm_value;
          }
          else{
            /* empty param for example ?utm_campaign= or ?utm_campaign */
            utm_nodes[i].value = empty_param_case;
          }
        }/* end for */
      }/* end if */
    }// end inner set_utm_feild function */
  }
</script>

expires

If you want to change Define when the cookie will be removed. Value must be a Number which will be interpreted as days from time of creation.

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

    Cookies.set('Lead', lead, { expires: 30 });

UPDATE (Dec 21) Dynamic params code:

Wants to add more params? do this here (REMEMBER: "utm" name === "class" name
***case sensitive )

image

step 1 - add “some_custom_parameter”:
image

step 2 - Add the match field manually inside the form (+ add class) :

<input type="text" class="some_custom_parameter" placeholder="some_custom_parameter" name="some_custom_parameter">

Add param:
www.hello.com?some_custom_parameter=hello-world

Publish :slight_smile:
image

2 Likes

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.

1 Like

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

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

Hi - thanks for this solution.

Is it possible to get the UTM parameters from the page and pass them directly into another custom code rather than input forms?

I have a custom code block which contains an iFrame to display on my landing page and I want to pass some of the utm parameters into the iFrame’s URL, as this will dynamically update the content in this iFrame.

So the custom code would look like:

Any help would be much appreciated

No way to know your issue without live URL + read-only.

Also, what do you mean her: “lead cookie in the 1st instant”

Yes. This is for example the value of utm_source (Inside setUTMformValues function).

JSON.parse(Cookies.get('Lead')).parameters.utm_source;

put this value in another custom code if you want.

let hello = JSON.parse(Cookies.get('Lead')).parameters.utm_source;
console.log(hello);

Anyway your Q is too general (You should know some JS to solve this -or- hire freelancer).

So we added in this code.

  1. The script wasn’t functioning, and we realized that JQuery wasn’t being called before the script - so we added that.

Now in the console we are getting "utm_sourceis exist etc.) so that part is looking good.

However the form fields which are entered before the submit are not seeing their values updated. Not sure what we are missing here.

You can see the page at: dominKnow|ONE Feature Release

FYI the fields are there, but we have them as “hidden” instead of “text”

Hey,

Is the code updated to work with the cookie? Cookie is working fine but not populating fields…

1 Like

I fixed the problem ==> update the answer (copy -paste the code again).

** Also Now the code works for more than one form on a page.

1 Like

Hi everyone
I’m new here
I used this tutorial but it’s not working for me
can someone help and tell me what I did wrong?
By the way
I’m not the one who generated the codes
They were sent to me from the digital marketing office of the company for which I built the site,
maybe there is a problem there?
Link to watch:
https://preview.webflow.com/preview/commit-9a6738?utm_medium=preview_link&utm_source=designer&utm_content=commit-9a6738&preview=4668d1cc1b0d22dd9eaa0f0e320ae169&pageId=610637511343eed7f6291cbc&workflow=preview

Thank you very much
Ilan

There is an error being listed

let isEmpty = jQuery.isEmptyObject(getAllUrlParams);

"Uncaught reference error: JQuery is not defined. "

I thought webflow loads JQuery as standard?
I don’t see any cookies being set or getting the utm values to populate. Is there a simpler exact guide out there for this? Do you need to do anything other than paste in that code and use the embed codes?

Paste the custom code before body (After webflow loads jquery).

Hi!

I have been testing this together with GDPR cookie consent.

As a first time visitor, if I accept the cookies on the page, the cookie appears correctly but as soon as I leave the page to go to another one on the website, the cookie disappears again and will not write anything on hidden form fields (Forms with hidden fields are presents on job openings at Jobs | bunq).

Cookie script is live and issue can be seen already on bunq.com. Can it be solved?

EDIT: If I go back a second time to the original page, the cookie sticks, but who does that. I also tested without cookie consent block, behaves the same.