GiacomoGalanti

custom task au

Jan 23rd, 2021
32
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.83 KB | None | 0 0
  1. function () {
  2. // customTask Builder by Simo Ahava
  3. //
  4. // More information about customTask: https://www.simoahava.com/analytics/customtask-the-guide/
  5. //
  6. // Change the default values for the settings below.
  7.  
  8. // Configure the following
  9. var maxBatch= 10,
  10. batchVariableName = '_impressions_batch',
  11. productIdAttribute = 'data-productid';
  12. // clientIdIndex: The Custom Dimension index to where you want to send the visitor's Client ID.
  13. // https://bit.ly/2Ms0ZcC
  14. var clientIdIndex = 1;
  15.  
  16. // hitTypeIndex: The Custom Dimension index to where you want to send the hit type of the request.
  17. // https://bit.ly/2KZqLA9
  18. var hitTypeIndex = 2;
  19.  
  20. // payloadLengthIndex: The Custom Dimension index to where you want to send the length of the payload of the request.
  21. // https://bit.ly/2PdhPKM
  22. var payloadLengthIndex = 3;
  23.  
  24. // removeCustomDefinitionsFromTimingHits: Set to true if you want to remove Custom Dimensions and Custom Metrics from the page speed timing hit.
  25. // https://bit.ly/2nGzw8T
  26. var removeCustomDefinitionsFromTimingHits = true;
  27.  
  28. // piiRegex: Array of {name, regex} objects, where the regular expression matches a pattern you want to replace with [REDACTED name].
  29. // https://bit.ly/2wcJym2
  30. var piiRegex = [{
  31. name: 'EMAIL',
  32. regex: /.{4}@.{4}/g
  33. }];
  34.  
  35. // transactionDeduper: Configuration object for preventing duplicate transactions from being recorded.
  36. // https://bit.ly/2AvSZ2Y
  37. var transactionDeduper = {
  38. keyName: '_transaction_ids',
  39. cookieExpiresDays: 365
  40. };
  41.  
  42. // obfuscate: Obfuscates the entire hit payload (using a dictionary of words consistently) and dispatches it to the trackingId you provide.
  43. // https://bit.ly/2RectUl
  44. var obfuscate = {
  45. tid: 'UA-12345-1',
  46. dict: ['tumble', 'noble', 'flourish', 'abandon', 'liberal', 'team', 'conflict', 'collar', 'tiger', 'stun', 'grace', 'resource', 'phantom', 'imagine', 'information', 'hall', 'sweet', 'agriculture', 'bingo', 'relative'],
  47. stringParams: ['uid','ua','dr','cn','cs','cm','ck','cc','ci','gclid','dclid','dl','dh','dp','dt','cd','cg[1-5]','linkid','an','aid','av','aiid','ec','ea','el','ti','ta','in','ic','iv','pr\d{1,3}id','pr\d{1,3}nm','pr\d{1,3}br','pr\d{1,3}ca','pr\d{1,3}va','pr\d{1,3}cc','pr\d{1,3}cd\d{1,3}','tcc','pal','col','il\d{1,3}nm','il\d{1,3}pi\d{1,3}id','il\d{1,3}pi\d{1,3}nm','il\d{1,3}pi\d{1,3}br','il\d{1,3}pi\d{1,3}ca','il\d{1,3}pi\d{1,3}va','il\d{1,3}pi\d{1,3}cd\d{1,3}','promo\d{1,3}id','promo\d{1,3}nm','promo\d{1,3}cr','promo\d{1,3}ps','sn','sa','st','utc','utv','utl','exd','cd\d{1,3}','xid','exp','_utmz'],
  48. priceParams: ['tr','ts','tt','ip','pr\d{1,3}pr','id\d{1,3}pi\d{1,3}pr'],
  49. priceModifier: Math.random(),
  50. medium: ['organic', 'referral', 'social', 'cpc'],
  51. replaceString: function(t){if(''===t)return t;'function'==typeof window.btoa&&(t=btoa(t));var n=t.split('').map(function(t){return t.charCodeAt(0)}).join('')%obfuscate.dict.length;return obfuscate.dict[n]},
  52. init: function(){var c=[];obfuscate.dict.forEach(function(t){obfuscate.dict.forEach(function(o){c.push(t+'-'+o)})}),obfuscate.dict=obfuscate.dict.concat(c)}
  53. };
  54.  
  55. // localStorageCid: Use localStorage to persist Client ID with Google Analytics tags
  56. // https://bit.ly/2GNElc4
  57. var localStorageCid = {
  58. objectName: 'ga_client_id',
  59. expires: 1000*60*60*24*365*2
  60. };
  61.  
  62. // DO NOT EDIT ANYTHING BELOW THIS LINE
  63. var targetElement = {{Click Element}},
  64. event = {{Event}};
  65.  
  66. if (event === 'gtm.click') {
  67. while (!targetElement.getAttribute(productIdAttribute) && targetElement.tagName !== 'BODY') {
  68. targetElement = targetElement.parentElement;
  69. }
  70. }
  71.  
  72. return function(customModel) {
  73. console.log(window[batchVariableName]);
  74.  
  75. // Set up the beforeunload listener only when the tag is first run.
  76. if (typeof window[batchVariableName] === 'undefined') {
  77. window.addEventListener('beforeunload', function() {
  78. window.dataLayer.push({
  79. event: 'sendFinalBatch'
  80. });
  81. });
  82. }
  83.  
  84. var shouldFire = false,
  85. batch = window[batchVariableName] = window[batchVariableName] || [],
  86. impressionId,
  87. ost;
  88.  
  89. if (event === 'gtm.elementVisibility') {
  90. impressionId = targetElement.getAttribute(productIdAttribute);
  91. batch.push(impressionId);
  92. if (batch.length === maxBatch) { shouldFire = true; }
  93. }
  94.  
  95. if (['sendFinalBatch', 'gtm.timer'].indexOf(event) > -1 && batch.length > 0) { shouldFire = true; }
  96.  
  97. if (event === 'gtm.click') { shouldFire = true; }
  98.  
  99. if (shouldFire) {
  100. ost = customModel.get('sendHitTask');
  101. customModel.set('sendHitTask', function(sendModel) {
  102. ost(sendModel);
  103. window[batchVariableName] = [];
  104. });
  105. } else {
  106. model.data.keys.forEach(function(key) {
  107. model.set(key, null);
  108. });
  109. }
  110. };
  111.  
  112.  
  113. if (typeof obfuscate === 'object' && typeof obfuscate.init === 'function') obfuscate.init();
  114.  
  115. var readFromStorage = function (key) {
  116. if (!window.Storage) {
  117. // From: https://stackoverflow.com/a/15724300/2367037
  118. var value = '; ' + document.cookie;
  119. var parts = value.split('; ' + key + '=');
  120. if (parts.length === 2) {
  121. return parts.pop().split(';').shift();
  122. }
  123. } else {
  124. return window.localStorage.getItem(key);
  125. }
  126. };
  127.  
  128. var writeToStorage = function (key, value, expireDays) {
  129. if (!window.Storage) {
  130. var expiresDate = new Date();
  131. expiresDate.setDate(expiresDate.getDate() + expireDays);
  132. document.cookie = key + '=' + value + ';expires=' + expiresDate.toUTCString();
  133. } else {
  134. window.localStorage.setItem(key, value);
  135. }
  136. };
  137.  
  138. var globalSendHitTaskName = '_ga_originalSendHitTask';
  139.  
  140. return function (customTaskModel) {
  141.  
  142. window[globalSendHitTaskName] = window[globalSendHitTaskName] || customTaskModel.get('sendHitTask');
  143.  
  144. // clientIdIndex
  145. if (typeof clientIdIndex === 'number') {
  146. customTaskModel.set('dimension' + clientIdIndex, customTaskModel.get('clientId'));
  147. }
  148. // /clientIdIndex
  149.  
  150. // hitTypeIndex
  151. if (typeof hitTypeIndex === 'number') {
  152. customTaskModel.set('dimension' + hitTypeIndex, customTaskModel.get('hitType'));
  153. }
  154. // /hitTypeIndex
  155.  
  156. // removeCustomDefinitionsFromTimingHits
  157. if (typeof removeCustomDefinitionsFromTimingHits === 'boolean' && removeCustomDefinitionsFromTimingHits === true) {
  158. if (customTaskModel.get('hitType') === 'timing') {
  159. var _rcd_tempFieldObject = {};
  160. var _rcd_dimensionIndex = 1;
  161. while (_rcd_dimensionIndex !== 201) {
  162. _rcd_tempFieldObject['dimension' + _rcd_dimensionIndex] = undefined;
  163. _rcd_tempFieldObject['metric' + _rcd_dimensionIndex] = undefined;
  164. _rcd_dimensionIndex++;
  165. }
  166. customTaskModel.set(_rcd_tempFieldObject);
  167. }
  168. }
  169. // /removeCustomDefinitionsFromTimingHits
  170.  
  171. // localStorageCid
  172. if (typeof localStorageCid === 'object' && typeof localStorageCid.objectName === 'string' && typeof localStorageCid.expires === 'number' && window.Storage) {
  173. var _lsc_clientId = customTaskModel.get('clientId');
  174. var _lsc_obj = JSON.stringify({
  175. clientId: _lsc_clientId,
  176. expires: new Date().getTime() + localStorageCid.expires
  177. });
  178. window.localStorage.setItem(localStorageCid.objectName, _lsc_obj);
  179. }
  180. // /localStorageCid
  181.  
  182. customTaskModel.set('sendHitTask', function (sendHitTaskModel) {
  183.  
  184. var originalSendHitTaskModel = sendHitTaskModel,
  185. originalSendHitTask = window[globalSendHitTaskName],
  186. canSendHit = true;
  187.  
  188. try {
  189.  
  190. // transactionDeduper
  191. if (typeof transactionDeduper === 'object' && transactionDeduper.hasOwnProperty('keyName') && transactionDeduper.hasOwnProperty('cookieExpiresDays') && typeof sendHitTaskModel.get('&ti') !== 'undefined') {
  192. var _td_transactionId = sendHitTaskModel.get('&ti');
  193. var _td_storedIds = JSON.parse(readFromStorage(transactionDeduper.keyName) || '[]');
  194. if (_td_storedIds.indexOf(_td_transactionId) > -1 && ['transaction', 'item'].indexOf(sendHitTaskModel.get('hitType')) === -1) {
  195. canSendHit = false;
  196. } else if (_td_storedIds.indexOf(_td_transactionId) === -1) {
  197. _td_storedIds.push(_td_transactionId);
  198. writeToStorage(transactionDeduper.keyName, JSON.stringify(_td_storedIds), transactionDeduper.cookieExpiresDays);
  199. }
  200. }
  201. // /transactionDeduper
  202.  
  203. // piiRegex
  204. if (typeof piiRegex !== 'undefined' && piiRegex.length) {
  205. var _pr_hitPayloadParts = sendHitTaskModel.get('hitPayload').split('&');
  206. for (var _pr_regexI = 0; _pr_regexI < _pr_hitPayloadParts.length; _pr_regexI++) {
  207. var _pr_param = _pr_hitPayloadParts[_pr_regexI].split('=');
  208. var _pr_val;
  209. try {
  210. _pr_val = decodeURIComponent(decodeURIComponent(_pr_param[1]));
  211. } catch(e) {
  212. _pr_val = decodeURIComponent(_pr_param[1]);
  213. }
  214. piiRegex.forEach(function(pii) {
  215. _pr_val = _pr_val.replace(pii.regex, '[REDACTED ' + pii.name + ']');
  216. });
  217. _pr_param[1] = encodeURIComponent(_pr_val);
  218. _pr_hitPayloadParts[_pr_regexI] = _pr_param.join('=');
  219. }
  220. sendHitTaskModel.set('hitPayload', _pr_hitPayloadParts.join('&'), true);
  221. }
  222. // /piiRegex
  223.  
  224. // payloadLengthIndex
  225. if (typeof payloadLengthIndex === 'number') {
  226. var _pl_hitPayload = sendHitTaskModel.get('hitPayload');
  227. _pl_hitPayload += '&cd' + payloadLengthIndex + '=';
  228. _pl_hitPayload += (_pl_hitPayload.length + _pl_hitPayload.length.toString().length);
  229. sendHitTaskModel.set('hitPayload', _pl_hitPayload, true);
  230. }
  231. // /payloadLengthIndex
  232.  
  233. if (canSendHit) {
  234. originalSendHitTask(sendHitTaskModel);
  235. }
  236.  
  237. // obfuscate
  238. if (typeof obfuscate === 'object' && obfuscate.hasOwnProperty('tid') && obfuscate.hasOwnProperty('dict') && obfuscate.hasOwnProperty('stringParams') && obfuscate.hasOwnProperty('priceParams') && obfuscate.hasOwnProperty('replaceString') && obfuscate.hasOwnProperty('priceModifier')) {
  239. var _o_hitPayload = sendHitTaskModel.get('hitPayload');
  240. obfuscate.stringParams.forEach(function(strParam) {
  241. var regexParam = new RegExp('[?&]' + strParam + '=[^&]+', 'g');
  242. var paramsInHitpayload = _o_hitPayload.match(regexParam) || [];
  243. paramsInHitpayload.forEach(function(keyValue) {
  244. var parts = keyValue.split('=');
  245. var urlParts = parts[1].split('%2F').map(function(urlPart) {
  246. if (/https?:/.test(decodeURIComponent(urlPart))) return urlPart;
  247. return urlPart.split('%20').map(function(wordPart) {
  248. return obfuscate.replaceString(wordPart);
  249. }).join('%20');
  250. }).join('%2F');
  251. _o_hitPayload = _o_hitPayload.replace(parts.join('='), parts[0] + '=' + urlParts);
  252. });
  253. });
  254. obfuscate.priceParams.forEach(function(prParam) {
  255. var regexParam = new RegExp('[?&]' + prParam + '=[^&]+', 'g');
  256. var paramsInHitpayload = _o_hitPayload.match(regexParam) || [];
  257. paramsInHitpayload.forEach(function(keyValue) {
  258. var parts = keyValue.split('=');
  259. var price = parseFloat(parts[1]) || 0.00;
  260. price = (price * obfuscate.priceModifier).toFixed(2);
  261. _o_hitPayload = _o_hitPayload.replace(parts.join('='), parts[0] + '=' + price);
  262. });
  263. });
  264. _o_hitPayload = _o_hitPayload
  265. .replace(
  266. '&tid=' + sendHitTaskModel.get('trackingId') + '&',
  267. '&tid=' + obfuscate.tid + '&'
  268. )
  269. .replace(/[?&]aip($|&|=[^&]*)/, '')
  270. .replace(/[?&]c[sm]=[^&]*/g, '')
  271. .replace(/[?&]uip=[^&]*/g, '');
  272. if (Math.random() <= 0.10) {
  273. _o_hitPayload +=
  274. '&cs=' + obfuscate.dict[Math.floor(Math.random()*obfuscate.dict.length)] +
  275. '&cm=' + obfuscate.medium[Math.floor(Math.random()*obfuscate.medium.length)];
  276. }
  277. _o_hitPayload += '&uip=' +
  278. (Math.floor(Math.random() * 255) + 1) + '.' +
  279. (Math.floor(Math.random() * 255) + 0) + '.' +
  280. (Math.floor(Math.random() * 255) + 0) + '.' +
  281. (Math.floor(Math.random() * 255) + 0);
  282. _o_hitPayload += '&aip=1';
  283. sendHitTaskModel.set('hitPayload', _o_hitPayload, true);
  284. originalSendHitTask(sendHitTaskModel);
  285. }
  286. // /obfuscate
  287.  
  288. } catch(err) {
  289. originalSendHitTask(originalSendHitTaskModel);
  290. }
  291.  
  292. });
  293.  
  294. };
  295. }
Add Comment
Please, Sign In to add comment