🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
Implement skip and mask patterns for URL tracking in analytics script
Bill Yang2f945a0f960a
diff --git a/server/public/script.js b/server/public/script.jsindex 14cba06e5..6cec4919a 100644--- a/server/public/script.js+++ b/server/public/script.js@@ -1,6 +1,5 @@// Rybbit Analytics Script(function () {- // Get the script tag that loaded this scriptconst scriptTag = document.currentScript;const ANALYTICS_HOST = scriptTag.getAttribute("src").split("/script.js")[0];@@ -19,15 +18,56 @@return;}- // Get debounce duration from data attribute or default to 500msconst debounceDuration = scriptTag.getAttribute("data-debounce")? Math.max(0, parseInt(scriptTag.getAttribute("data-debounce"))): 500;- // Check if automatic URL tracking should be disabledconst autoTrackURLs = scriptTag.getAttribute("data-auto-track") !== "false";- // Debounce function+ let skipPatterns = [];+ try {+ const skipAttr = scriptTag.getAttribute("data-skip-patterns");+ if (skipAttr) {+ skipPatterns = JSON.parse(skipAttr);+ if (!Array.isArray(skipPatterns)) skipPatterns = [];+ }+ } catch (e) {+ console.error("Error parsing data-skip-patterns:", e);+ }++ let maskPatterns = [];+ try {+ const maskAttr = scriptTag.getAttribute("data-mask-patterns");+ if (maskAttr) {+ maskPatterns = JSON.parse(maskAttr);+ if (!Array.isArray(maskPatterns)) maskPatterns = [];+ }+ } catch (e) {+ console.error("Error parsing data-mask-patterns:", e);+ }++ // Helper function to convert wildcard pattern to regex+ function patternToRegex(pattern) {+ // Escape regex special characters, then replace * with [^/]++ const escaped = pattern.replace(/[\.\+\?\^\$\(\)\[\]\{\}]/g, "\\$&");+ const regexString = escaped.replace(/\*/g, "[^/]+");+ return new RegExp(`^${regexString}$`);+ }++ function findMatchingPattern(path, patterns) {+ for (const pattern of patterns) {+ try {+ const regex = patternToRegex(pattern);+ if (regex.test(path)) {+ return pattern; // Return the pattern string itself+ }+ } catch (e) {+ console.error(`Invalid pattern: ${pattern}`, e);+ }+ }+ return null;+ }+function debounce(func, wait) {let timeout;return (...args) => {@@ -36,9 +76,7 @@};}- // Unified tracking function for all event typesconst track = (eventType = "pageview", eventName = "", properties = {}) => {- // Validate event dataif (eventType === "custom_event" &&(!eventName || typeof eventName !== "string")@@ -50,10 +88,21 @@}const url = new URL(window.location.href);+ let pathname = url.pathname;++ if (findMatchingPattern(pathname, skipPatterns)) {+ return;+ }++ const maskMatch = findMatchingPattern(pathname, maskPatterns);+ if (maskMatch) {+ pathname = maskMatch;+ }+const payload = {site_id: SITE_ID,hostname: url.hostname,- pathname: url.pathname,+ pathname: pathname,querystring: url.search,screenWidth: window.innerWidth,screenHeight: window.innerHeight,@@ -66,9 +115,6 @@eventType === "custom_event" ? JSON.stringify(properties) : undefined,};- console.log(`${eventType} event:`, payload);-- // Use the new unified endpointfetch(`${ANALYTICS_HOST}/track`, {method: "POST",headers: {@@ -80,18 +126,14 @@}).catch(console.error);};- // Helper function for pageviewsconst trackPageview = () => track("pageview");- // Create debounced version with configured durationconst debouncedTrackPageview =debounceDuration > 0? debounce(trackPageview, debounceDuration): trackPageview;- // Only set up automatic URL change tracking if not disabledif (autoTrackURLs) {- // History API overrideconst originalPushState = history.pushState;const originalReplaceState = history.replaceState;@@ -105,19 +147,14 @@debouncedTrackPageview();};- // Handle navigation eventswindow.addEventListener("popstate", debouncedTrackPageview);}- // Expose APIwindow.frogstats = {- // Core tracking functiontrack,- // Helper functions for backward compatibility and conveniencepageview: trackPageview,event: (name, properties = {}) => track("custom_event", name, properties),};- // Initial pageviewtrackPageview();})();