Advertisement
Guest User

Untitled

a guest
Nov 29th, 2018
388
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Pass Tracking Parameters to a Form on Another Page Using GTM
  2. // http://zackphilipps.com/store-gclid-cookie-send-to-hubspot/
  3.  
  4. function getCookie(name) {
  5.   var value = '; ' + document.cookie;
  6.   var parts = value.split('; ' + name + '=');
  7.   if (parts.length == 2)
  8.     return parts.pop().split(';').shift();
  9. }
  10.  
  11. function setCookie(name, value, days) {
  12.   var date = new Date();
  13.   date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
  14.   var expires = '; expires=' + date.toGMTString();
  15.   document.cookie = name + '=' + value + expires + ';path=/';
  16. }
  17.  
  18. function getParam(p) {
  19.   var match = RegExp('[?&]' + p + '=([^&]*)').exec(window.location.search);
  20.   return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
  21. }
  22.  
  23. function assignTrackingParameterToCookie(fieldParam, formType) {
  24.   var field = getParam(fieldParam),
  25.     inputs;
  26.   if(field) {
  27.     setCookie(fieldParam, field, 365);
  28.   }
  29.   if(formType == 'gform') {
  30.     inputs = document.querySelectorAll('.' + fieldParam + ' input[type="text"]');
  31.     assignCookieValueToFormInput(fieldParam, inputs);
  32.   } else if(formType == 'hubspot') {
  33.     inputs = document.querySelectorAll('.hs-input[name="gclid__c"]');
  34.     assignCookieValueToFormInput(fieldParam, inputs);
  35.   }
  36. }
  37.  
  38. function assignCookieValueToFormInput(fieldParam, inputs) {
  39.   var field = getCookie(fieldParam),
  40.     length = inputs.length;
  41.   if(field && length) {
  42.     for(var i = 0; i < length; i++) {
  43.       inputs[i].value = field;
  44.     }
  45.   }
  46. }
  47.  
  48. assignTrackingParameterToCookie('gclid', 'hubspot');
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement