In this example, we will be setting 4 different cookies and we’ll show you how to set many more.
utm_source
utm_medium
utm_campaign
some_random_param
1. Parse The URL
First create a function that will pull parameters from the URL
Here you can see that if you give the URL parameters, it will return the value
2. Add the Cookie Library
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.
3. Set the cookie values! (Bake those Cookies)
We will set the cookies if they exist.
what is this doing:
- loop through ALL the params you want to track.
- if the parameter exists in the URL, store the cookie.
- if the parameter does not exist, then it will leave the cookie as-is.
- find an input by the name of the parameter, example:
$('input[name=utm_source]')
- if the cookie value exists and the input for the same name exists, replace the value