simple-metrics-tracker
Version:
Simple Metrics Tracker is a lightweight cookie-free JavaScript library for tracking user interactions and events on your website. Please visits simplemetrics.ru for more information
2 lines (1 loc) • 5.8 kB
JavaScript
((h,r)=>{let n="Simple Metrics",p="1.2.5",a="https://api.simplemetrics.ru/events",e=h.navigator.userAgent,i=r.body||{};var o=r.currentScript;let c=h.document.documentElement||{};function t(t,e){return t&&t.getAttribute("data-"+e)}let C=function(){var t=h.location.host;return-1==t.indexOf(".")||/^[0-9.:]+$/.test(t)},g=t(o,"token"),u=t(o,"mode")??"normal",s=t(o,"navigation")??"push",l="true"==t(o,"debug"),d="true"==t(o,"debugrequests"),m=function(t,...e){l&&console.log(n+":",t,...e)},f=function(t){console.warn(n+":",t)},P=function(){var t=/(bot|spider|crawl)/i.test(e)&&!/(cubot)/i.test(e);return h.navigator.webdriver||h.__nightmare||h.callPhantom||h._phantom||h.phantom||h.__polypane||h._bot||t||Math.random()==Math.random()},v=function(){let e=h.crypto||h.msCrypto;var n=[1e7]+-1e3+-4e3+-8e3+-1e11,a=/[018]/g;try{return n.replace(a,function(t){return(t^e.getRandomValues(new Uint8Array(1))[0]&15>>t/4).toString(16)})}catch(t){return n.replace(a,function(t){var e=16*Math.random()|0;return(t<2?e:3&e|8).toString(16)})}},y=function(){try{var t=c.clientHeight||0,e=Math.max(i.scrollHeight||0,i.offsetHeight||0,c.clientHeight||0,c.scrollHeight||0,c.offsetHeight||0);return Math.min(100,5*Math.round(100*((c.scrollTop||0)+t)/e/5))}catch(t){return f(t),0}},$=function(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch(t){return f(t),null}},B=function(){return{width:h.screen.width,height:h.screen.height}},T=function(){return{width:Math.max(c.clientWidth||0,h.innerWidth||0)||null,height:Math.max(c.clientHeight||0,h.innerHeight||0)||null}},w=function(t){return"function"==typeof t},U=function(){let t="";try{t=decodeURIComponent(h.location.pathname)}catch(t){f(t)}return"hash"===u&&h.location.hash&&(t+=h.location.hash.split("?")[0]),t},j=function(){return h.location.search.slice(1).split("&").filter(function(t){return new RegExp("^((utm_)(source|medium|content|term|campaign))=").test(t)}).join("&")||null},q=function(){var t=h.performance;let e;try{e=t.getEntriesByType("navigation")[0].type}catch(t){f(t)}return e?-1<["reload","back_forward"].indexOf(e):t&&t.navigation&&-1<[1,2].indexOf(t.navigation.type)};function W(){var t=y();D<t&&(D=t)}function b(e){if(M)I(e);else try{z(I.bind(null,e))}catch(t){f(t),I(e)}}function E(t,e){t?(m("track Custom Event",t,e),t=t.replace(/[^a-z0-9]+/gi,"_").replace(/(^_|_$)/g,""),t=x(v(),"custom_event",t,!1,e),V(t)):f("the custom event does not have name and cannot be tracked")}let J=v(),S=((r.referrer||"").replace(/^https?:\/\/((m|l|w{2,3}([0-9]+)?)\.)?([^?#]+)(.*)$/,"$4").replace(/^([^/]+)$/,"$1")||null)??"(direct)",_="",H=Date.now(),k=0,D=0,M=!1,A=null,O=null,z=function(e){var t=h.navigator.userAgentData;t&&w(t.getHighEntropyValues)?h.navigator.userAgentData.getHighEntropyValues(["platform","platformVersion"]).then(function(t){M=!0,A=t.platform,O=t.platformVersion,e()}).catch(function(t){m(t),e()}):(m("UserAgentData or getHighEntropyValues are not supported"),e())},V=function(e){m(e),l&&!d||((new Image).src=a+"/simple.gif?"+Object.keys(e).filter(function(t){return null!=e[t]}).map(function(t){return encodeURIComponent(t)+"="+encodeURIComponent(e[t])}).join("&")+"&time="+Date.now())},F=function(t){var e;m(t),l&&!d||(h.navigator.sendBeacon?(e=new Blob([JSON.stringify(t)],{type:"application/json"}),h.navigator.sendBeacon(a+"/append",e)):(V(t),m("Beacon is not supported")))},x=function(t,e,n,a,i){var r=a?S:null,a=a?j():null,{width:o,height:c}=B(),{width:u,height:s}=T(),l=h.navigator.userAgentData,d=l?.mobile,l=l?JSON.stringify(l.brands):null;if("custom_event"!==e||null!==n)return{id:t,sessionId:J,token:g,type:e,customName:"custom_event"===e?n:null,bot:P(),path:U(),referrer:r,utmQueryParams:a,userAgent:h.navigator.userAgent,osName:A,osVersion:O,mobile:d,brands:l,timezone:$(),language:h.navigator.language,screenWidth:o,screenHeight:c,viewportWidth:u,viewportHeight:s,metadata:i?JSON.stringify(i):null,version:p};f("customName must be specified for custom events!")},Q=function(t){m("track Page View"),_=v();t=x(_,"page_view",null,t);V(t)},L=function(){m("track Page Leave");var t={id:_,token:g,type:"append",duration:Math.round((Date.now()-H-k)/1e3)??0,scroll:Math.max(0,D,y())??0};k=0,H=Date.now(),F(t)},I=function(t){t&&L();var e=h.location.host,e=!!S&&S.split("/")[0]==e,n=(m("sameSite",e),q()),t=!t&&!n&&!e;Q(t)};{m("Initialising SimpleMetrics tracking script..."),m("Running in "+(l?"debug":"production")+" mode"),m("Version: "+p),C()&&!l&&f("Running in localhost in non-debug mode! Please set data-debug=true to avoid tracking"),h[o="simplemetrics_loaded"]&&f("The script is loaded twice"),h[o]=!0,r.doctype||f("Add DOCTYPE html for accurate dimensions"),m("data-token =",g),m("data-mode =",u),m("data-navigation =",s),m("data-debug =",l),m("data-debug-requests =",d);let t;if(h.addEventListener("visibilitychange",function(){m("visibilitychange "+h.document.hidden),h.document.hidden?("onpagehide"in h||L(),t=Date.now()):k+=Date.now()-t},!1),h.addEventListener("pagehide",L,!1),h.addEventListener("load",function(){D=y(),this.addEventListener("scroll",W,!1)}),"normal"==u){let t=h.history;(t?t.pushState:void 0)&&Event&&h.dispatchEvent&&(o=function(a){let i=t[a];return function(){var t=arguments,e=i.apply(this,t);let n;return w(Event)?n=new Event(a):(n=r.createEvent("Event")).initEvent(a,!0,!0),n.arguments=t,h.dispatchEvent(n),e}},"replace"===s?t.replaceState=o("replaceState"):t.pushState=o("pushState"));let e="replace"===s?"replaceState":"pushState";h.addEventListener(e,function(){m(e),b(!0)},!1),h.addEventListener("popstate",function(){m("popState"),b(!0)},!1)}function Y(t,e){E(t,e)}if("hash"==u&&h.addEventListener("hashchange",function(){m("hashchange"),b(!0)}),h[o="sm_event"]){var N,R=h[o],R=R&&R.q?R.q:[];h[o]=Y;for(N of R)E(N.eventName,N.metadata)}else h[o]=Y;b(!1)}})(window,document);