@usertrax/tracker
Version:
Privacy-friendly conversion tracking and A/B testing script for UserTrax
1 lines • 17.2 kB
JavaScript
(()=>{"use strict";function t(e){return t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},t(e)}function e(e,r,n){return(r=function(e){var r=function(e){if("object"!=t(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,"string");if("object"!=t(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==t(r)?r:r+""}(r))in e?Object.defineProperty(e,r,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[r]=n,e}function r(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),r.push.apply(r,n)}return r}function n(t){for(var n=1;n<arguments.length;n++){var o=null!=arguments[n]?arguments[n]:{};n%2?r(Object(o),!0).forEach((function(r){e(t,r,o[r])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(o)):r(Object(o)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(o,e))}))}return t}var o={endpoint:"https://api.usertrax.io/api/tracker/conversion",sessionEndpoint:"https://api.usertrax.io/api/tracker/session",pageviewEndpoint:"https://api.usertrax.io/api/tracker/pageview",autoTrack:!0,enableABTesting:!0,enableCrossDomainTracking:!0,crossDomainParamName:"uxs",crossDomainDomains:[],sessionTimeout:864e5};function a(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=Array(e);r<e;r++)n[r]=t[r];return n}function i(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var r=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=r){var n,o,a,i,c=[],s=!0,u=!1;try{if(a=(r=r.call(t)).next,0===e){if(Object(r)!==r)return;s=!1}else for(;!(s=(n=a.call(r)).done)&&(c.push(n.value),c.length!==e);s=!0);}catch(t){u=!0,o=t}finally{try{if(!s&&null!=r.return&&(i=r.return(),Object(i)!==i))return}finally{if(u)throw o}}return c}}(t,e)||function(t,e){if(t){if("string"==typeof t)return a(t,e);var r={}.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?a(t,e):void 0}}(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function c(){var t=new URLSearchParams(window.location.search),e={gclid:t.get("gclid"),gclsrc:t.get("gclsrc"),dclid:t.get("dclid"),fbclid:t.get("fbclid"),fbc:t.get("fbc"),fbp:t.get("fbp"),msclkid:t.get("msclkid"),ttclid:t.get("ttclid")};t.forEach((function(t,r){r.startsWith("utm_")&&(e[r]=t)})),e.gclid&&(localStorage.setItem("usertrax_gclid",e.gclid),localStorage.setItem("usertrax_gclid_timestamp",Date.now())),e.gclsrc&&localStorage.setItem("usertrax_gclsrc",e.gclsrc),e.dclid&&localStorage.setItem("usertrax_dclid",e.dclid),e.msclkid&&(localStorage.setItem("usertrax_msclkid",e.msclkid),localStorage.setItem("usertrax_msclkid_timestamp",Date.now())),e.fbclid&&(localStorage.setItem("usertrax_fbclid",e.fbclid),localStorage.setItem("usertrax_fbclid_timestamp",Date.now())),e.fbc&&localStorage.setItem("usertrax_fbc",e.fbc),e.fbp&&localStorage.setItem("usertrax_fbp",e.fbp),e.ttclid&&(localStorage.setItem("usertrax_ttclid",e.ttclid),localStorage.setItem("usertrax_ttclid_timestamp",Date.now()));var r={};return Object.entries(e).forEach((function(t){var e=i(t,2),n=e[0],o=e[1];n.startsWith("utm_")&&o&&(r[n]=o)})),Object.keys(r).length>0&&localStorage.setItem("usertrax_utm",JSON.stringify(r)),e}function s(){return{gclid:localStorage.getItem("usertrax_gclid")||"",gclsrc:localStorage.getItem("usertrax_gclsrc")||"",dclid:localStorage.getItem("usertrax_dclid")||"",fbclid:localStorage.getItem("usertrax_fbclid")||"",fbc:localStorage.getItem("usertrax_fbc")||"",fbp:localStorage.getItem("usertrax_fbp")||"",adcell:localStorage.getItem("adcell")||"",msclkid:localStorage.getItem("usertrax_msclkid")||"",ttclid:localStorage.getItem("usertrax_ttclid")||"",utm:JSON.parse(localStorage.getItem("usertrax_utm"))||{}}}function u(t){var e=sessionStorage.getItem("uxs_id"),r=sessionStorage.getItem("uxs_timestamp"),n=new URLSearchParams(window.location.search).get(t.crossDomainParamName);if(n&&t.enableCrossDomainTracking)e=n,sessionStorage.setItem("uxs_id",e),sessionStorage.setItem("uxs_timestamp",Date.now().toString());else{var o=t.sessionTimeout||864e5,a=Date.now();e&&r&&a-parseInt(r)<o||(e="usertrax_"+Date.now()+"_"+Math.random().toString(36).substr(2,9),sessionStorage.setItem("uxs_id",e)),sessionStorage.setItem("uxs_timestamp",a.toString())}return e}function l(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),r.push.apply(r,n)}return r}var f={},d=!1;function m(){var t=document.querySelectorAll("[data-usertrax-ab-test-group]"),e={};t.forEach((function(t){var r=t.getAttribute("data-usertrax-ab-test-group");e[r]||(e[r]=[]),e[r].push(t)})),Object.entries(e).forEach((function(t){var e=i(t,2),r=e[0],n=e[1],o=f[r];n.find((function(t){return t.hasAttribute("data-usertrax-ab-test-fallback")})),n.forEach((function(t){var e=t.getAttribute("data-usertrax-ab-test-variant"),r=t.hasAttribute("data-usertrax-ab-test-fallback");o?e===o?t.style.removeProperty("display"):t.style.display="none":r?t.style.removeProperty("display"):t.style.display="none"}))}))}function p(){if(Object.keys(f).length>0)return function(t){for(var r=1;r<arguments.length;r++){var n=null!=arguments[r]?arguments[r]:{};r%2?l(Object(n),!0).forEach((function(r){e(t,r,n[r])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):l(Object(n)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(n,e))}))}return t}({},f);for(var t={},r=0;r<sessionStorage.length;r++){var n=sessionStorage.key(r);n&&n.startsWith("usertrax_ab_")&&(t[n.replace("usertrax_ab_","")]=sessionStorage.getItem(n))}return t}function b(t){return f[t]||sessionStorage.getItem("usertrax_ab_".concat(t))||null}function g(){if(d)m();else{var t=document.querySelectorAll("[data-usertrax-ab-test-group]"),e={};t.forEach((function(t){var r=t.getAttribute("data-usertrax-ab-test-group");e[r]||(e[r]=[]),e[r].push(t)})),Object.entries(e).forEach((function(t){var e=i(t,2);e[0],e[1].forEach((function(t){t.hasAttribute("data-usertrax-ab-test-fallback")?t.style.removeProperty("display"):t.style.display="none"}))})),new MutationObserver((function(t){t.forEach((function(t){t.addedNodes.forEach((function(t){if(t.nodeType===Node.ELEMENT_NODE){var e=t.querySelectorAll?t.querySelectorAll("[data-usertrax-ab-test-group]"):[];t.matches&&t.matches("[data-usertrax-ab-test-group]")&&e.push(t);var r={};e.forEach((function(t){var e=t.getAttribute("data-usertrax-ab-test-group");r[e]||(r[e]=[]),r[e].push(t)})),Object.entries(r).forEach((function(t){var e=i(t,2);e[0],e[1].forEach((function(t){t.hasAttribute("data-usertrax-ab-test-fallback")?t.style.removeProperty("display"):t.style.display="none"}))}))}}))}))})).observe(document.body,{childList:!0,subtree:!0})}}function y(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),r.push.apply(r,n)}return r}function h(){var t=document.currentScript||document.querySelector("script[data-key]");return t?t.getAttribute("data-key"):null}function w(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return window.fetch?fetch(t,e):new Promise((function(r,n){var o=new XMLHttpRequest;o.open(e.method||"GET",t),o.onload=function(){o.status>=200&&o.status<300?r({ok:!0,json:function(){return Promise.resolve(JSON.parse(o.responseText))}}):n(new Error(o.statusText))},o.onerror=function(){return n(new Error("Network Error"))},o.send(e.body)}))}function v(t){var r=function(t){for(var r=1;r<arguments.length;r++){var n=null!=arguments[r]?arguments[r]:{};r%2?y(Object(n),!0).forEach((function(r){e(t,r,n[r])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):y(Object(n)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(n,e))}))}return t}({},t);return Object.keys(r).forEach((function(t){r[t]||0===r[t]||delete r[t]})),r}function O(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),r.push.apply(r,n)}return r}function x(t){for(var r=1;r<arguments.length;r++){var n=null!=arguments[r]?arguments[r]:{};r%2?O(Object(n),!0).forEach((function(r){e(t,r,n[r])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):O(Object(n)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(n,e))}))}return t}Date.now(),Date.now();var S=Date.now(),j=0;function _(t){var e=u(t),r=h();if(r){S=Date.now(),j=0;var n=p(),o=Object.keys(n).length>0?JSON.stringify(n):null,a=null;if(performance.timing){var i=performance.timing.navigationStart,c=performance.timing.loadEventEnd;if(i>0&&c>0&&c>i){var s=c-i;s>0&&s<=6e4&&(a=s)}}if(null===a&&window.performance&&window.performance.getEntriesByType)try{var l=performance.getEntriesByType("navigation");if(l&&l.length>0){var f=l[0],d=Math.round(f.loadEventEnd-f.fetchStart);d>0&&d<=6e4&&(a=d)}}catch(t){}var m=v({session_id:e,url:window.location.href,page_title:document.title||"",referrer:document.referrer||"",viewport_width:window.innerWidth,viewport_height:window.innerHeight,screen_width:screen.width,screen_height:screen.height,load_time_ms:a,ab_test_variant:o});w(t.pageviewEndpoint,{method:"POST",body:JSON.stringify(m),mode:"cors",headers:{Accept:"application/json","Content-Type":"application/json","X-Auth-Key":r||""},keepalive:!0}).then((function(t){return t.json()})).then((function(t){})).catch((function(t){}))}}function E(){var t=window.pageYOffset||document.documentElement.scrollTop,e=window.innerHeight,r=Math.max(document.body.scrollHeight,document.body.offsetHeight,document.documentElement.clientHeight,document.documentElement.scrollHeight,document.documentElement.offsetHeight),n=Math.round((t+e)/r*100);j=Math.max(j,n)}function P(){Math.round((Date.now()-S)/1e3)}function k(t,e,r){var n=s(),o=e.endpoint,a=h(),i=r||"unknown",c=p(),u=v({gclid:t.gclid||n.gclid||"",fbclid:t.fbclid||n.fbclid||"",fbc:t.fbc||n.fbc||"",fbp:t.fbp||n.fbp||"",adcell:t.adcell||n.adcell||"",msclkid:t.msclkid||n.msclkid||"",ttclid:t.ttclid||n.ttclid||"",utm:t.utm||n.utm||"",id:t.id||"",total:t.total||"",event:t.event||"",label:t.label||"",currency:t.currency||"",metadata:t.metadata||{},session_id:i,ab_test_data:Object.keys(c).length>0?c:null});return w("".concat(o),{method:"POST",body:JSON.stringify(u),mode:"cors",headers:{Accept:"application/json","Content-Type":"application/json","X-Auth-Key":a||""},keepalive:!0}).then((function(t){return t.json()})).then((function(t){return t})).catch((function(t){throw t}))}function D(t,e,r){var n=t.href;if(n)try{var o=new URL(n),a=window.location.hostname,i=o.hostname;if(i!==a&&function(t,e){return!!e.enableCrossDomainTracking&&(!e.crossDomainDomains||0===e.crossDomainDomains.length||e.crossDomainDomains.some((function(e){return t===e||t.endsWith("."+e)})))}(i,e)){var c=r();c&&!o.searchParams.has(e.crossDomainParamName)&&(o.searchParams.set(e.crossDomainParamName,c),t.href=o.toString())}}catch(t){}}function I(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),r.push.apply(r,n)}return r}function A(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=Array(e);r<e;r++)n[r]=t[r];return n}!function(){if(window.usertrax=window.usertrax||[],window.usertraxConfig=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return n(n({},o),t)}(window.usertraxConfig||{}),"undefined"!=typeof window&&window.usertrax&&(window.usertrax.getVariant=b,window.usertrax.getAssignments=p,window.usertrax.applyElementVisibility=m),c(),document.addEventListener("click",(function(t){var r=t.target.closest("[data-usertrax]");if(r){var n,o={},a=function(t,e){var r="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!r){if(Array.isArray(t)||(r=function(t,e){if(t){if("string"==typeof t)return A(t,e);var r={}.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?A(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){r&&(t=r);var n=0,o=function(){};return{s:o,n:function(){return n>=t.length?{done:!0}:{done:!1,value:t[n++]}},e:function(t){throw t},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,i=!0,c=!1;return{s:function(){r=r.call(t)},n:function(){var t=r.next();return i=t.done,t},e:function(t){c=!0,a=t},f:function(){try{i||null==r.return||r.return()}finally{if(c)throw a}}}}(r.attributes);try{for(a.s();!(n=a.n()).done;){var i=n.value;i.name.startsWith("data-usertrax-")&&(o[i.name.replace("data-usertrax-","")]=i.value)}}catch(t){a.e(t)}finally{a.f()}r.dataset.usertrax&&(o.event=r.dataset.usertrax);var c=function(t){for(var r=1;r<arguments.length;r++){var n=null!=arguments[r]?arguments[r]:{};r%2?I(Object(n),!0).forEach((function(r){e(t,r,n[r])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):I(Object(n)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(n,e))}))}return t}({},o);window.usertrax.push(c)}})),a=window.usertraxConfig,l=function(){return u(window.usertraxConfig)},a.enableCrossDomainTracking&&(document.querySelectorAll("a[href]").forEach((function(t){D(t,a,l)})),document.addEventListener("click",(function(t){var e=t.target.closest("a");e&&D(e,a,l)}))),!1!==window.usertraxConfig.autoTrack){var t=function(){var t;_(window.usertraxConfig),t=null,window.addEventListener("scroll",(function(){t&&clearTimeout(t),t=setTimeout(E,100)})),document.addEventListener("click",(function(){Date.now()})),document.addEventListener("visibilitychange",(function(){"hidden"===document.visibilityState&&P()})),window.addEventListener("beforeunload",(function(){P()}));var e=window.location.href;setInterval((function(){window.location.href!==e&&(e=window.location.href,_(window.usertraxConfig))}),1e3)},r=function(){(function(t){var e,r,n,o,a=u(t),l=s(),p=(e=navigator.userAgent,r="desktop",n="unknown",o="unknown",/Mobile|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(e)?r=/iPad/i.test(e)?"tablet":"mobile":/Tablet/i.test(e)&&(r="tablet"),e.indexOf("Chrome")>-1?n="Chrome":e.indexOf("Firefox")>-1?n="Firefox":e.indexOf("Safari")>-1?n="Safari":e.indexOf("Edge")>-1?n="Edge":e.indexOf("Opera")>-1&&(n="Opera"),e.indexOf("Windows")>-1?o="Windows":e.indexOf("Mac")>-1?o="macOS":e.indexOf("Linux")>-1?o="Linux":e.indexOf("Android")>-1?o="Android":e.indexOf("iOS")>-1&&(o="iOS"),{deviceType:r,browser:n,os:o}),b=c(),g=v(x(x({session_id:a,initial_referrer:document.referrer||"",initial_landing_page:window.location.href,device_type:p.deviceType,browser:p.browser,os:p.os},l),b)),y=t.sessionEndpoint,O=h(),S=encodeURIComponent(window.location.href);return w("".concat(y,"?url=").concat(S),{method:"POST",body:JSON.stringify(g),mode:"cors",headers:{Accept:"application/json","Content-Type":"application/json","X-Auth-Key":O||""},keepalive:!0}).then((function(t){return t.json()})).then((function(e){if(e.ab_test_config&&t.enableABTesting){var r=e.ab_test_config;r.active_tests&&r.user_assignments&&(o=r.user_assignments,f=o||{},d=!0,Object.entries(o).forEach((function(t){var e=i(t,2),r=e[0],n=e[1];sessionStorage.setItem("usertrax_ab_".concat(r),n)})),(n=r.active_tests)&&n.length&&(n.forEach((function(t){var e=f[t.test_key];if(e){var r=t.variants.find((function(t){return t.key===e}));if(r){if(r.css){var n=document.createElement("style");n.textContent=r.css,n.setAttribute("data-ab-test",t.test_key),n.setAttribute("data-ab-variant",e),document.head.appendChild(n)}if(r.js)try{new Function("variant","testKey","usertrax",r.js)(e,t.test_key,window.usertrax)}catch(t){}sessionStorage.setItem("usertrax_ab_".concat(t.test_key),e)}}})),m()))}var n,o;return e})).catch((function(t){throw t}))})(window.usertraxConfig).then((function(){g(),t()})).catch((function(e){g(),t()}))};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",(function(){r()})):r()}var a,l;function y(){for(;window.usertrax.length>0;)k(window.usertrax.shift(),window.usertraxConfig,u(window.usertraxConfig))}var O=window.usertrax.push;window.usertrax.push=function(){for(var t=arguments.length,e=new Array(t),r=0;r<t;r++)e[r]=arguments[r];O.apply(this,e),y()},y()}()})();