How to Use Cookies to Capture URL Parameters

In this example, we will be setting 4 different cookies and we’ll show you how to set many more.

  1. utm_source
  2. utm_medium
  3. utm_campaign
  4. some_random_param

1. Parse The URL

First create a function that will pull parameters from the URL

function getParameterByName(name) {
  name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
  var regex = new RegExp('[\\?&]' + name + '=([^&#]*)'),
    results = regex.exec(location.search);
  return results === null
    ? ''
    : decodeURIComponent(results[1].replace(/\+/g, ' '));
}

Here you can see that if you give the URL parameters, it will return the value

var pValue = getParameterByName('utm_source');

I would recommend using js-cookie because it is light-weight and does not require jQuery but IS compatible with jQuery.

Here I have included js-cookie from https://rawgit.com/ CDN.

  <script type="text/javascript" src="//cdn.rawgit.com/js-cookie/js-cookie/8b70250875f7e07445b6a457f9c2474ead4cba44/src/js.cookie.js"></script>

We will set the cookies if they exist.

var all_the_params_to_track = [
  'utm_source',
  'utm_medium',
  'utm_campaign',
  'some_random_param'
];

all_params_to_persist.forEach(function(param) {
  var pValue = getParameterByName(param);
  if (pValue != null || pValue != '') {
    Cookies.set(param, pValue);
  }

  var cValue = Cookies.set(param);
  var input = $('input[name='+ param +']')
  if (input && (cValue != null || cValue != '')) {
    input.val(cValue);  
  }
});

what is this doing:

Blair Anderson is the creator of Tachyons Templates.


Blog Posts

Template Categories