Advertisement
vapvarun

Set Cookies from url parameters

Mar 2nd, 2020
1,084
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
jQuery 1.24 KB | None | 0 0
  1. <script src="https://cdn.jsdelivr.net/npm/js-cookie@beta/dist/js.cookie.min.js"></script>
  2.  
  3. <script type="module">
  4.  
  5. // Parse the URL
  6. function getParameterByName(name) {
  7.     name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
  8.     var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
  9.         results = regex.exec(location.search);
  10.     return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
  11. }
  12. // Give the URL parameters variable names
  13. var source = getParameterByName('utm_source');
  14. var medium = getParameterByName('utm_medium');
  15. var campaign = getParameterByName('utm_campaign');
  16.  
  17. // Set the cookies
  18. if(Cookies.get('utm_source') == null || Cookies.get('utm_source') == "") {
  19. Cookies.set('utm_source', source);
  20. }
  21. if(Cookies.get('utm_medium') == null || Cookies.get('utm_medium') == "") {
  22. Cookies.set('utm_medium', medium);
  23. }
  24. if(Cookies.get('utm_campaign') == null || Cookies.get('utm_campaign') == "") {
  25. Cookies.set('utm_campaign', campaign);
  26. }
  27.  
  28. // Grab the cookie value and set the form field values
  29. $(document).ready(function(){
  30.     $('input[name=utm_source').val(utm_source);
  31.     $('input[name=utm_medium').val(utm_medium);
  32.     $('input[name=utm_campaign').val(utm_campaign);
  33. });
  34.   Cookies.set('vapvarun', 'bar')
  35. </script>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement