UNPKG

auto-roi-calc-web-events-tracking

Version:

A wrapper for the AutoROICalc custom web events tracking JavaScript module.

1 lines 7.44 kB
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.AutoRoiCalc=t():e.AutoRoiCalc=t()}(this,()=>(()=>{"use strict";var e={};return(()=>{var t=e;const o={google:["google.com","google.sk","google.cz","google.co.uk"],bing:["bing.com"],yahoo:["yahoo.com"],duckduckgo:["duckduckgo.com"],yandex:["yandex.com","yandex.ru"],baidu:["baidu.com"],ecosia:["ecosia.org"],startpage:["startpage.com"],ask:["ask.com"],naver:["naver.com"],aol:["aol.com"],seznam:["seznam.cz"]},r=["gclid","fbclid","yclid","yclid_v2","yclid_fingerprint","cpc_","sklik","etarget"],i="|";let n=new class{constructor(){this.trackingId="",this.config={debug:!1,maxSources:6,cookieNameSources:"arc_sources",storageNameTimeout:"arc_timeout",storageNameTimeoutSent:"arc_timeout_sent",storageNameSources:"arc_sources",timeout:60,ignoreUtmCampaign:!1,ignoreUtmSource:!1,useSourceMedium:!0}}debugLog(e){this.config.debug&&console.log(e)}setTrackingId(e){this.debugLog(`Setting tracking id: ${e}`),this.trackingId=e}setConfig(e,t){return this.debugLog(`Setting config value ${t} for key ${e}`),!(!(e in this.config)||("debug"==e&&"boolean"==typeof t?(this.config.debug=t,0):"maxSources"==e&&"number"==typeof t&&t>0&&t<7?(this.config.maxSources=t,0):"cookieNameSources"==e&&"string"==typeof t?(this.config.cookieNameSources=t,0):"storageNameTimeout"==e&&"string"==typeof t?(this.config.storageNameTimeout=t,0):"storageNameTimeoutSent"==e&&"string"==typeof t?(this.config.storageNameTimeoutSent=t,0):"storageNameSources"==e&&"string"==typeof t?(this.config.storageNameSources=t,0):"timeout"==e&&"number"==typeof t&&t>0?(this.config.timeout=t,0):"ignoreUtmCampaign"==e&&"boolean"==typeof t?(this.config.ignoreUtmCampaign=t,0):"ignoreUtmSource"==e&&"boolean"==typeof t?(this.config.ignoreUtmSource=t,0):"useSourceMedium"!=e||"boolean"!=typeof t||(this.config.useSourceMedium=t,0)))}getConfig(){return this.debugLog("Getting config."),this.config}getUrlParams(){return new URLSearchParams(window.location.search)}getStorageItem(e){try{return localStorage.getItem(e)}catch(e){return this.config.debug&&console.error("Local storage get error:",e),null}}setStorageItem(e,t){try{return localStorage.setItem(e,t),!0}catch(e){return this.config.debug&&console.error("Local storage set error:",e),!1}}isHostOrSubdomain(e,t){return e===t||e.endsWith("."+t)}getHostname(e){try{return new URL(e).hostname.replace(/^www\./,"").toLowerCase()}catch(e){return this.config.debug&&console.error("URL parse error:",e),null}}getSearchEngine(e){for(let t of Object.keys(o))for(let r of o[t])if(this.isHostOrSubdomain(e,r))return t;return null}hasCpcIndicator(){let e=this.getUrlParams();for(let t of r)if(e.has(t))return!0;if(document.referrer)try{let e=new URL(document.referrer).searchParams;for(let t of r)if(e.has(t))return!0}catch(e){}return!1}getArcSource(){let e=this.getUrlParams();return this.debugLog(`Getting arc_source url parameter: ${e.get("arc_source")}`),e.get("arc_source")}getCampaign(){if(this.config.ignoreUtmCampaign)return this.debugLog("Getting utm_campaign is set to be ignored."),null;let e=this.getUrlParams();return this.debugLog(`Getting utm_campaign url parameter: ${e.get("utm_campaign")}`),e.get("utm_campaign")}getSource(){let e=this.getUrlParams().get("utm_source");return this.config.ignoreUtmSource||!e?(this.debugLog("Getting utm_source is set to be ignored or no utm_source value found."),this.getReferrer()):(this.debugLog(`Getting utm_source url parameter: ${e}`),e)}getMedium(){this.debugLog("Getting medium...");let e=this.getUrlParams().get("utm_medium");if(e)return this.debugLog(`Medium found in utm_medium url param: ${e}`),e;this.debugLog("Checking if is cpc...");let t=document.referrer,o=t?this.getHostname(t):null,r=o?this.getSearchEngine(o):null;return r&&this.hasCpcIndicator()?(this.debugLog("Is cpc..."),"cpc"):(this.debugLog("Checking if is organic..."),r?(this.debugLog("Is organic..."),"organic"):(this.debugLog("Checking if is (none)..."),"(direct)"==this.getReferrer()?(this.debugLog("Is (none)..."),"(none)"):(this.debugLog("Resolving as referral."),"referral")))}getSourceMedium(){let e=this.getSource(),t=this.getMedium();return this.debugLog("Getting source / medium: "+e+" / "+t),e+" / "+t}getReferrer(){let e=document.referrer;if(e){let t=this.getHostname(e),o=this.getHostname(window.location.href);if(!t)return"(direct)";if(this.debugLog(`Got referrer from document.referrer: ${t}`),o&&t===o)return this.debugLog(`Referrer matches current location: ${t}. Falling back to (direct)`),"(direct)";let r=this.getSearchEngine(t);return r?(this.debugLog(`Is search engine: ${r}`),r):t}return this.debugLog("document.referrer not set, giving: (direct)"),"(direct)"}getTheSource(){this.debugLog("Getting the AutoROICalc source...");let e=this.getArcSource();return e||(this.getCampaign()||(this.config.useSourceMedium?this.getSourceMedium():this.getSource()))}isTimeoutExpired(e){this.debugLog("Timeout check is set.");let t=parseInt(this.getStorageItem(e)||"");return!(t&&(new Date).getTime()-t<=60*this.config.timeout*1e3&&(this.debugLog("Not expired, aborting."),1))}appendNewSource(e="",t=!0,o=""){let r=o||this.config.storageNameTimeout;if(this.debugLog("Appending new source..."),t&&!this.isTimeoutExpired(r))return!1;let n=this.getSources();if(e)this.debugLog(`Pushing custom source: ${e}`),n.includes(e)||n.push(e);else{let e=this.getTheSource();this.debugLog(`Pushing source determined by session: ${e}`),n.includes(e)||n.push(e)}return n.length>this.config.maxSources&&(this.debugLog("Removing residual sources..."),n=n.slice(-this.config.maxSources)),this.setStorageItem(this.config.storageNameSources,n.join(i)),this.setStorageItem(r,(new Date).getTime().toString()),!0}getSources(e=!0){this.debugLog("Getting previous sources from the local storage...");let t=[],o=this.getStorageItem(this.config.storageNameSources);return o&&(t=o.split(i)),e&&(t=[...new Set(t)]),t}send(e,t,o=1,r=!0,n="",s="",g=""){let c=n||this.config.storageNameTimeoutSent;if(this.debugLog("Starting to send the event..."),!this.trackingId||!e||!t)return this.debugLog("Tracking ID, Record Type, or Description is not set. Aborting."),!1;if(r&&!this.isTimeoutExpired(c))return!1;let u="https://api.autoroicalc.com/record/collect_web_event";u+="?trackingId="+encodeURIComponent(this.trackingId),u+="&type="+encodeURIComponent(e),u+="&desc="+encodeURIComponent(t),u+="&sources="+encodeURIComponent(s||this.getSources().join(i)),u+="&value="+encodeURIComponent(o);let a=Array.isArray(g)?g.join("|"):g;return a&&(u+="&tags="+encodeURIComponent(a)),this.debugLog(`Sending the event to ${u}`),this.setStorageItem(c,(new Date).getTime().toString()),fetch(u,{mode:"no-cors"}).then(()=>{this.config.debug&&console.log("Event sent successfully.")}).catch(e=>{this.config.debug&&console.error("Fetch error:",e)}),!0}setCookie(){document.cookie=this.config.cookieNameSources+"="+encodeURIComponent(this.getSources().join(i))+"; path=/; SameSite=Lax"}};t.appendNewSource=function(e="",t=!0,o=""){return n.appendNewSource(e,t,o)},t.getSources=function(e=!0){return n.getSources(e)},t.setTrackingId=function(e){n.setTrackingId(e)},t.setConfig=function(e,t){return n.setConfig(e,t)},t.getConfig=function(){return n.getConfig()},t.sendEvent=function(e,t,o=1,r=!0,i="",s="",g=""){return n.send(e,t,o,r,i,s,g)},t.setSourcesCookie=function(){n.setCookie()}})(),e})());