mirror of
https://github.com/rybbit-io/rybbit.git
synced 2025-05-17 23:11:44 +02:00
1 line
No EOL
2.7 KiB
JavaScript
1 line
No EOL
2.7 KiB
JavaScript
!function(){let t=document.currentScript,e=t.getAttribute("src").split("/script.js")[0];if(!e){console.error("Please provide a valid analytics host");return}let r=t.getAttribute("data-site-id")||t.getAttribute("site-id");if(!r||isNaN(Number(r))){console.error("Please provide a valid site ID using the data-site-id attribute");return}let a=t.getAttribute("data-debounce")?Math.max(0,parseInt(t.getAttribute("data-debounce"))):500,n="false"!==t.getAttribute("data-track-spa"),i="false"!==t.getAttribute("data-track-query"),s="false"!==t.getAttribute("data-track-outbound"),o=[];try{let u=t.getAttribute("data-skip-patterns");u&&(o=JSON.parse(u),Array.isArray(o)||(o=[]))}catch(l){console.error("Error parsing data-skip-patterns:",l)}let c=[];try{let p=t.getAttribute("data-mask-patterns");p&&(c=JSON.parse(p),Array.isArray(c)||(c=[]))}catch(d){console.error("Error parsing data-mask-patterns:",d)}function g(t){let e="__DOUBLE_ASTERISK_TOKEN__",r="__SINGLE_ASTERISK_TOKEN__",a=t.replace(/\*\*/g,e).replace(/\*/g,r).replace(/[.+?^${}()|[\]\\]/g,"\\$&"),n=(a=a.replace(/\//g,"\\/")).replace(RegExp(e,"g"),".*").replace(RegExp(r,"g"),"[^/]+");return RegExp("^"+n+"$")}function f(t,e){for(let r of e)try{let a=g(r);if(a.test(t))return r}catch(n){console.error(`Invalid pattern: ${r}`,n)}return null}let h=(t="pageview",a="",n={})=>{if("custom_event"===t&&(!a||"string"!=typeof a)){console.error("Event name is required and must be a string for custom events");return}let s=new URL(window.location.href),u=s.pathname;if(f(u,o))return;let l=f(u,c);l&&(u=l);let p={site_id:r,hostname:s.hostname,pathname:u,querystring:i?s.search:"",screenWidth:window.innerWidth,screenHeight:window.innerHeight,language:navigator.language,page_title:document.title,referrer:document.referrer,type:t,event_name:a,properties:"custom_event"===t||"outbound"===t?JSON.stringify(n):void 0};fetch(`${e}/track`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p),mode:"cors",keepalive:!0}).catch(console.error)},b=()=>h("pageview"),v=a>0?function t(e,r){let a;return(...t)=>{clearTimeout(a),a=setTimeout(()=>e.apply(this,t),r)}}(b,a):b;if(s&&document.addEventListener("click",function(t){let e=t.target.closest("a");e&&e.href&&function t(e){try{let r=window.location.hostname,a=new URL(e).hostname;return a!==r&&""!==a}catch(n){return!1}}(e.href)&&h("outbound","",{url:e.href,text:e.innerText||e.textContent||"",target:e.target||"_self"})}),n){let y=history.pushState,m=history.replaceState;history.pushState=function(...t){y.apply(this,t),v()},history.replaceState=function(...t){m.apply(this,t),v()},window.addEventListener("popstate",v)}window.rybbit={pageview:b,event:(t,e={})=>h("custom_event",t,e),trackOutbound:(t,e="",r="_self")=>h("outbound","",{url:t,text:e,target:r})},b()}(); |