From e9867d2adbf2f429470e919201e855b43bdf8af1 Mon Sep 17 00:00:00 2001 From: Sam Van Campenhout Date: Thu, 14 Oct 2021 11:15:45 +0200 Subject: [PATCH] Respect `localStorage.plausible_ignore` This change ensures no events are sent if `localStorage.plausible_ignore` is set to `"true"`. This behaviour is consistent with the standalone script. --- README.md | 6 ++++++ src/lib/request.spec.ts | 12 ++++++++++++ src/lib/request.ts | 8 ++++++++ 3 files changed, 26 insertions(+) diff --git a/README.md b/README.md index a524232..7638d86 100644 --- a/README.md +++ b/README.md @@ -239,5 +239,11 @@ const cleanup = enableAutoOutboundTracking() cleanup() ``` +### Opt out and exclude yourself from the analytics + +Since plausible-tracker is bundled with your application code, using an ad-blocker to exclude your visits isn't an option. Fortunately Plausible has an alternative for this scenario: plausible-tracker will not send events if `localStorage.plausible_ignore` is set to `"true"`. + +More information about this method can be found in the [Plausible documentation](https://plausible.io/docs/excluding-localstorage). + ## Reference documentation For the full method and type documentation, check out the [reference documentation](https://plausible-tracker.netlify.app). diff --git a/src/lib/request.spec.ts b/src/lib/request.spec.ts index 8b5a068..b561f9d 100644 --- a/src/lib/request.spec.ts +++ b/src/lib/request.spec.ts @@ -111,6 +111,18 @@ describe('sendEvent', () => { sendEvent('myEvent', { ...defaultData, trackLocalhost: true }); expect(xmr).toHaveBeenCalled(); }); + test('does not send if "plausible_ignore" is set to "true" in localStorage', () => { + window.localStorage.setItem('plausible_ignore', 'true'); + expect(xmr).not.toHaveBeenCalled(); + sendEvent('myEvent', defaultData); + expect(xmr).not.toHaveBeenCalled(); + + window.localStorage.setItem('plausible_ignore', 'something-not-true'); + sendEvent('myEvent', defaultData); + expect(xmr).toHaveBeenCalled(); + + window.localStorage.removeItem('plausible_ignore'); + }); test('calls callback', () => { expect(xmr).not.toHaveBeenCalled(); const callback = jest.fn(); diff --git a/src/lib/request.ts b/src/lib/request.ts index 389288e..8867bce 100644 --- a/src/lib/request.ts +++ b/src/lib/request.ts @@ -48,6 +48,14 @@ export function sendEvent( ); } + const shouldIgnoreCurrentBrowser = + localStorage.getItem('plausible_ignore') === 'true'; + if (shouldIgnoreCurrentBrowser) { + return console.warn( + '[Plausible] Ignoring event because "plausible_ignore" is set to "true" in localStorage' + ); + } + const payload: EventPayload = { n: eventName, u: data.url,