Skip to content

🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.

feat: add auto track initial pageview option to ScriptBuilder and update documentation

Bill Yangb731e0bf5ee1
diff --git a/client/src/components/SiteSettings/ScriptBuilder.tsx b/client/src/components/SiteSettings/ScriptBuilder.tsx
index 0a01dca17..b6cf315eb 100644
--- a/client/src/components/SiteSettings/ScriptBuilder.tsx
+++ b/client/src/components/SiteSettings/ScriptBuilder.tsx
@@ -15,6 +15,7 @@ interface ScriptBuilderProps {
export function ScriptBuilder({ siteId }: ScriptBuilderProps) {
// Script configuration options
const [debounceValue, setDebounceValue] = useState(500);
+ const [autoTrackPageview, setAutoTrackPageview] = useState(true);
const [autoTrack, setAutoTrack] = useState(true);
const [trackQuery, setTrackQuery] = useState(true);
const [trackOutbound, setTrackOutbound] = useState(true);
@@ -94,6 +95,11 @@ export function ScriptBuilder({ siteId }: ScriptBuilderProps) {
? `
data-debounce="${debounceValue}"`
: ""
+ }${
+ !autoTrackPageview
+ ? `
+ data-auto-track-pageview="false"`
+ : ""
}${
!autoTrack
? `
@@ -138,6 +144,28 @@ export function ScriptBuilder({ siteId }: ScriptBuilderProps) {
{/* Script Options Section */}
<div className="space-y-4">
+ {/* Auto Track Initial Pageview Option */}
+ <div className="space-y-2">
+ <div className="flex items-center justify-between">
+ <div>
+ <Label
+ htmlFor="autoTrackPageview"
+ className="text-sm font-medium text-foreground block"
+ >
+ Automatically track initial pageview
+ </Label>
+ <p className="text-xs text-muted-foreground mt-1">
+ Track the first pageview when the script loads
+ </p>
+ </div>
+ <Switch
+ id="autoTrackPageview"
+ checked={autoTrackPageview}
+ onCheckedChange={setAutoTrackPageview}
+ />
+ </div>
+ </div>
+
{/* Auto Track (SPA) Option */}
<div className="space-y-2">
<div className="flex items-center justify-between">
diff --git a/docs/src/content/script.mdx b/docs/src/content/script.mdx
index bc58b3a0e..0741315ea 100644
--- a/docs/src/content/script.mdx
+++ b/docs/src/content/script.mdx
@@ -17,6 +17,7 @@ If you are self-hosting Rybbit `app.rybbit.io` will be domain of your Rybbit ins
You can customize the script's behavior using `data-*` attributes on the `<script>` tag:
| Attribute | Type | Default | Description |
| :---------------- | :--------- | :------ | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `data-auto-track-pageview` | `string` | `"true"` | Set to `"false"` to disable automatic tracking of the initial pageview when the script loads. You will need to manually call `window.rybbit.pageview()` to track pageviews. |
| `data-track-spa` | `string` | `"true"`| Set to `"false"` to disable automatic pageview tracking for single page applications (React, Vue, etc). You will need to manually call `window.rybbit.pageview()` or `window.rybbit.track()` for all but the initial pageview. |
| `data-track-query`| `string` | `"true"`| Set to `"false"` to disable tracking of URL query strings. This enhances privacy by preventing potentially sensitive information in query parameters from being stored in your analytics data. |
| `data-skip-patterns` | `string` | `[]` | A JSON string array of URL path patterns to ignore. Pageviews matching these patterns won't be tracked. Supports two types of wildcards: `*` (matches within a segment) and `**` (matches across segments). |
diff --git a/server/public/script-full.js b/server/public/script-full.js
index d39014b73..0b18679d4 100644
--- a/server/public/script-full.js
+++ b/server/public/script-full.js
@@ -27,6 +27,8 @@
scriptTag.getAttribute("data-track-query") !== "false";
const trackOutbound =
scriptTag.getAttribute("data-track-outbound") !== "false";
+ const autoTrackPageview =
+ scriptTag.getAttribute("data-auto-track-pageview") !== "false";
let skipPatterns = [];
try {
@@ -207,5 +209,7 @@
track("outbound", "", { url, text, target }),
};
- trackPageview();
+ if (autoTrackPageview) {
+ trackPageview();
+ }
})();
diff --git a/server/public/script.js b/server/public/script.js
index 7c2b73179..a96f3d955 100644
--- a/server/public/script.js
+++ b/server/public/script.js
@@ -1 +1 @@
-!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()}();
\ No newline at end of file
+!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="false"!==t.getAttribute("data-auto-track-pageview"),u=[];try{let l=t.getAttribute("data-skip-patterns");l&&(u=JSON.parse(l),Array.isArray(u)||(u=[]))}catch(c){console.error("Error parsing data-skip-patterns:",c)}let p=[];try{let d=t.getAttribute("data-mask-patterns");d&&(p=JSON.parse(d),Array.isArray(p)||(p=[]))}catch(g){console.error("Error parsing data-mask-patterns:",g)}function f(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 h(t,e){for(let r of e)try{let a=f(r);if(a.test(t))return r}catch(n){console.error(`Invalid pattern: ${r}`,n)}return null}let b=(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),o=s.pathname;if(h(o,u))return;let l=h(o,p);l&&(o=l);let c={site_id:r,hostname:s.hostname,pathname:o,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(c),mode:"cors",keepalive:!0}).catch(console.error)},v=()=>b("pageview"),y=a>0?function t(e,r){let a;return(...t)=>{clearTimeout(a),a=setTimeout(()=>e.apply(this,t),r)}}(v,a):v;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)&&b("outbound","",{url:e.href,text:e.innerText||e.textContent||"",target:e.target||"_self"})}),n){let m=history.pushState,A=history.replaceState;history.pushState=function(...t){m.apply(this,t),y()},history.replaceState=function(...t){A.apply(this,t),y()},window.addEventListener("popstate",y)}window.rybbit={pageview:v,event:(t,e={})=>b("custom_event",t,e),trackOutbound:(t,e="",r="_self")=>b("outbound","",{url:t,text:e,target:r})},o&&v()}();
\ No newline at end of file