🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
Enhance outbound link tracking and update documentation
Bill Yang196f953b8388
diff --git a/docs/src/content/tracker.mdx b/docs/src/content/tracker.mdxindex da8e0107b..433486a6a 100644--- a/docs/src/content/tracker.mdx+++ b/docs/src/content/tracker.mdx@@ -29,19 +29,50 @@ Set to `"false"` to disable tracking of URL query strings. This enhances privacy- **Default:** `"true"`- **Example:** `data-track-query="false"`+### `data-track-outbound`++Set to `"false"` to disable automatic tracking of outbound link clicks. When enabled, the script automatically detects when a user clicks on a link to an external domain and tracks it with an event type of "outbound".++- **Default:** `"true"`+- **Example:** `data-track-outbound="false"`+### `data-skip-patterns`-A JSON string array of URL path patterns to ignore. Pageviews matching these patterns won't be tracked. Use `*` as a wildcard for path segments (e.g., `/admin/*`).+A JSON string array of URL path patterns to ignore. Pageviews matching these patterns won't be tracked. Supports two types of wildcards:++- `*` - Matches any characters within a single path segment (doesn't match across `/`)+- `**` - Matches any characters across multiple path segments (includes `/`)++Examples of pattern matching:+- `/admin/*` matches `/admin/dashboard` but not `/admin/users/list`+- `/admin/**` matches both `/admin/dashboard` and `/admin/users/list`+- `/blog/*/comments` matches `/blog/post-123/comments` but not `/blog/category/post/comments`+- `/blog/**/comments` matches any comments page regardless of path depth- **Default:** `[]`-- **Example:** `data-skip-patterns='["/admin", "/blog/*/edit"]'`+- **Example configuration:**+ ```html+ data-skip-patterns='["/admin/**", "/blog/drafts/*", "/preview/**"]'+ ```### `data-mask-patterns`-A JSON string array of URL path patterns to mask. Pageviews matching these patterns will be tracked, but the `pathname` sent will be replaced with the matching pattern string (e.g., `/users/*/profile`).+A JSON string array of URL path patterns to mask for privacy. Pageviews matching these patterns will be tracked, but the actual URL path will be replaced with the pattern itself in analytics data.++Supports the same wildcard patterns as `data-skip-patterns`:+- `*` - Single path segment wildcard+- `**` - Multi-segment wildcard++Common use cases:+- Mask user-specific pages: `/users/*/profile` will show as `/users/*/profile` instead of the actual username+- Mask all product pages: `/products/**` will hide specific product paths+- Mask order confirmation pages: `/checkout/*/confirmation` will hide order IDs- **Default:** `[]`-- **Example:** `data-mask-patterns='["/users/*/settings", "/order/*"]'`+- **Example configuration:**+ ```html+ data-mask-patterns='["/users/*/settings", "/accounts/**", "/orders/*/details"]'+ ```### `data-debounce`@@ -58,11 +89,11 @@ The delay (in milliseconds) before tracking a pageview after URL changes via thesrc="https://api.rybbit.io/api/script.js"asyncdata-site-id="456"- data-host="https://rybbit.mycompany.com"- data-auto-track="false"- data-skip-patterns='["/admin"]'- data-mask-patterns='["/user/*/dashboard"]'+ data-skip-patterns='["/admin/**", "/preview/*"]'+ data-mask-patterns='["/users/*/profile", "/orders/**"]'data-track-query="false"+ data-track-outbound="true"+ data-debounce="300"></script>```@@ -74,7 +105,7 @@ The script exposes a global object `window.rybbit` with functions for manual traThe core function to send tracking data.-* `eventType` (String): The type of event. Defaults to `"pageview"`. Use `"custom_event"` for custom events.+* `eventType` (String): The type of event. Defaults to `"pageview"`. Other values include `"custom_event"` or `"outbound"`.* `eventName` (String): The name of the custom event (max 255 characters). **Required** when `eventType` is `"custom_event"`.* `properties` (Object, Optional): An object containing custom data (max 8192 characters / 8KB when stringified). This will be JSON-stringified before sending.@@ -91,11 +122,18 @@ window.rybbit.track("custom_event", "Item Added To Cart", {price: 49.99,category: "Clothing"});++// Track an outbound link click manually+window.rybbit.track("outbound", "", {+ url: "https://example.com",+ text: "Visit Example Site",+ target: "_blank"+});```### `window.rybbit.pageview()`-A convenience function for tracking a pageview. Equivalent to `window.rybbit.track('pageview')`. Useful when `data-auto-track` is set to `"false"`.+A convenience function for tracking a pageview. Equivalent to `window.rybbit.track('pageview')`. Useful when `data-track-spa` is set to `"false"`.```javascriptwindow.rybbit.pageview();@@ -106,8 +144,21 @@ window.rybbit.pageview();A convenience function for tracking custom events. Equivalent to `window.rybbit.track('custom_event', eventName, properties)`.* `eventName` (String): The name of the custom event (max 255 characters).-* `properties` (Object, Optional): An object containing custom data (max 2048 characters / 2KB when stringified).+* `properties` (Object, Optional): An object containing custom data.```javascriptwindow.rybbit.event("Video Played", { videoId: "xyz789" });```++### `window.rybbit.trackOutbound(url, text, target)`++A convenience function for manually tracking outbound link clicks. Useful for programmatic navigation or custom link handling.++* `url` (String): The full URL of the outbound link.+* `text` (String, Optional): The text content of the link.+* `target` (String, Optional): The target attribute of the link (defaults to "_self").++```javascript+// Track a programmatic navigation to an external site+window.rybbit.trackOutbound("https://example.com", "Example Site", "_blank");+```diff --git a/server/public/script.js b/server/public/script.jsindex 00253db0b..1873325e6 100644--- a/server/public/script.js+++ b/server/public/script.js@@ -25,6 +25,8 @@const autoTrackSpa = scriptTag.getAttribute("data-track-spa") !== "false";const trackQuerystring =scriptTag.getAttribute("data-track-query") !== "false";+ const trackOutbound =+ scriptTag.getAttribute("data-track-outbound") !== "false";let skipPatterns = [];try {@@ -50,10 +52,27 @@// Helper function to convert wildcard pattern to regexfunction patternToRegex(pattern) {- // Escape regex special characters, then replace * with [^/]+- const escaped = pattern.replace(/[\.\+\?\^\$\(\)\[\]\{\}]/g, "\\$&");- const regexString = escaped.replace(/\*/g, "[^/]+");- return new RegExp(`^${regexString}$`);+ // Use a safer approach by replacing wildcards with unique tokens first+ const DOUBLE_WILDCARD_TOKEN = "__DOUBLE_ASTERISK_TOKEN__";+ const SINGLE_WILDCARD_TOKEN = "__SINGLE_ASTERISK_TOKEN__";++ // Replace wildcards with tokens+ let tokenized = pattern+ .replace(/\*\*/g, DOUBLE_WILDCARD_TOKEN)+ .replace(/\*/g, SINGLE_WILDCARD_TOKEN);++ // Escape special regex characters+ let escaped = tokenized.replace(/[.+?^${}()|[\]\\]/g, "\\$&");++ // Escape forward slashes+ escaped = escaped.replace(/\//g, "\\/");++ // Replace tokens with appropriate regex patterns+ let regexPattern = escaped+ .replace(new RegExp(DOUBLE_WILDCARD_TOKEN, "g"), ".*")+ .replace(new RegExp(SINGLE_WILDCARD_TOKEN, "g"), "[^/]+");++ return new RegExp("^" + regexPattern + "$");}function findMatchingPattern(path, patterns) {@@ -78,6 +97,17 @@};}+ // Check if a URL is an outbound link+ function isOutboundLink(url) {+ try {+ const currentHost = window.location.hostname;+ const linkHost = new URL(url).hostname;+ return linkHost !== currentHost && linkHost !== "";+ } catch (e) {+ return false;+ }+ }+const track = (eventType = "pageview", eventName = "", properties = {}) => {if (eventType === "custom_event" &&@@ -114,7 +144,9 @@type: eventType,event_name: eventName,properties:- eventType === "custom_event" ? JSON.stringify(properties) : undefined,+ eventType === "custom_event" || eventType === "outbound"+ ? JSON.stringify(properties)+ : undefined,};fetch(`${ANALYTICS_HOST}/track`, {@@ -135,6 +167,22 @@? debounce(trackPageview, debounceDuration): trackPageview;+ // Track outbound link clicks+ if (trackOutbound) {+ document.addEventListener("click", function (e) {+ const link = e.target.closest("a");+ if (!link || !link.href) return;++ if (isOutboundLink(link.href)) {+ track("outbound", "", {+ url: link.href,+ text: link.innerText || link.textContent || "",+ target: link.target || "_self",+ });+ }+ });+ }+if (autoTrackSpa) {const originalPushState = history.pushState;const originalReplaceState = history.replaceState;@@ -156,6 +204,8 @@track,pageview: trackPageview,event: (name, properties = {}) => track("custom_event", name, properties),+ trackOutbound: (url, text = "", target = "_self") =>+ track("outbound", "", { url, text, target }),};trackPageview();diff --git a/test/about.html b/test/about.htmldeleted file mode 100644index 58ffcc353..000000000--- a/test/about.html+++ /dev/null@@ -1,28 +0,0 @@-<!DOCTYPE html>-<html lang="en">-<head>- <meta charset="UTF-8">- <meta name="viewport" content="width=device-width, initial-scale=1.0">- <title>Test Site - About</title>- <link rel="stylesheet" href="styles.css">-</head>-<body>- <header>- <h1>About Us</h1>- <nav>- <ul>- <li><a href="index.html">Home</a></li>- <li><a href="about.html">About</a></li>- <li><a href="contact.html">Contact</a></li>- </ul>- </nav>- </header>- <main>- <p>This is the about page of the test site. Here you can learn more about us.</p>- </main>- <footer>- <p>© 2025 Test Site</p>- </footer>- <script src="http://localhost:3001/script.js"></script>-</body>-</html>\ No newline at end of filediff --git a/test/contact.html b/test/contact.htmldeleted file mode 100644index af0f92b9c..000000000--- a/test/contact.html+++ /dev/null@@ -1,28 +0,0 @@-<!DOCTYPE html>-<html lang="en">-<head>- <meta charset="UTF-8">- <meta name="viewport" content="width=device-width, initial-scale=1.0">- <title>Test Site - Contact</title>- <link rel="stylesheet" href="styles.css">-</head>-<body>- <header>- <h1>Contact Us</h1>- <nav>- <ul>- <li><a href="index.html">Home</a></li>- <li><a href="about.html">About</a></li>- <li><a href="contact.html">Contact</a></li>- </ul>- </nav>- </header>- <main>- <p>This is the contact page of the test site. Feel free to reach out to us.</p>- </main>- <footer>- <p>© 2025 Test Site</p>- </footer>- <script src="http://localhost:3001/script.js"></script>-</body>-</html>\ No newline at end of filediff --git a/test/index.html b/test/index.htmldeleted file mode 100644index d9d207d38..000000000--- a/test/index.html+++ /dev/null@@ -1,28 +0,0 @@-<!DOCTYPE html>-<html lang="en">-<head>- <meta charset="UTF-8">- <meta name="viewport" content="width=device-width, initial-scale=1.0">- <title>Test Site - Home</title>- <link rel="stylesheet" href="styles.css">-</head>-<body>- <header>- <h1>Welcome to the Test Site</h1>- <nav>- <ul>- <li><a href="index.html">Home</a></li>- <li><a href="about.html">About</a></li>- <li><a href="contact.html">Contact</a></li>- </ul>- </nav>- </header>- <main>- <p>This is the home page of the test site. Use the navigation links to explore other pages.</p>- </main>- <footer>- <p>© 2025 Test Site</p>- </footer>- <script src="http://localhost:3001/script.js"></script>-</body>-</html>\ No newline at end of filediff --git a/test/styles.css b/test/styles.cssdeleted file mode 100644index ffd7a8197..000000000--- a/test/styles.css+++ /dev/null@@ -1,42 +0,0 @@-body {- font-family: Arial, sans-serif;- margin: 0;- padding: 0;- line-height: 1.6;-}--header {- background: #333;- color: #fff;- padding: 10px 0;- text-align: center;-}--nav ul {- list-style: none;- padding: 0;-}--nav ul li {- display: inline;- margin-right: 10px;-}--nav ul li a {- color: #fff;- text-decoration: none;-}--main {- padding: 20px;-}--footer {- background: #333;- color: #fff;- text-align: center;- padding: 10px 0;- position: fixed;- bottom: 0;- width: 100%;-}\ No newline at end of file