plausible / plausible-tracker

Frontend library to interact with Plausible Analytics
https://github.com/plausible/plausible-tracker
MIT License
214 stars 46 forks source link

Error in `sendEvent` when `localStorage` is null or otherwise unavailable #25

Closed ellotheth closed 2 years ago

ellotheth commented 2 years ago

Versions

Describe the bug

I'm using Plausible with ReactJS, and I enable automatic pageview tracking:

import Plausible from "plausible-tracker";

const plausible = Plausible({domain: 'my-domain'});

// Context setup, routes, yadda yadda

plausible.enableAutoPageviews();

If localStorage is null or disabled (e.g. Block all cookies in Chromium 98), plausible.enableAutoPageviews() throws an error:

TypeError: Cannot read properties of null (reading 'getItem')
  at sendEvent(./node_modules/plausible-tracker/build/module/lib/request.js:13:53)
  at trackEvent(./node_modules/plausible-tracker/build/module/lib/tracker.js:51:9)
  at trackPageview(./node_modules/plausible-tracker/build/module/lib/tracker.js:54:9)
  at enableAutoPageviews(./node_modules/plausible-tracker/build/module/lib/tracker.js:73:9)
  at moduleId(./spa/js/index.jsx:114:11)

Expected behavior

Tracking should continue as if the plausible_ignore key were unset.

Steps to reproduce

  1. Disable localStorage in your browser of choice
  2. Load a page that uses plausible.enableAutoPageviews()

Your Environment

ellotheth commented 2 years ago

In case anybody else hits this, I've got a (very temporary) workaround that wraps Plausible operations and eats any errors:

const safe = (callback, args) => {
    try {
        return callback(...args);
    } catch (e) {
        // fail silently
    }
}

const safePlausible = plausible => ({
    trackEvent: (...args) => safe(plausible.trackEvent, args),
    trackPageview: (...args) => safe(plausible.trackPageview, args),
    enableAutoPageviews: (...args) => safe(plausible.enableAutoPageviews, args),
    enableAutoOutboundTracking: (...args) => safe(plausible.enableAutoOutboundTracking, args),
});

const plausible = safePlausible(Plausible(options));
sedubois commented 2 years ago

Using plausible-tracker@0.3.5, I am encountering the same error Cannot read properties of null (reading 'getItem') when calling plausible.trackPageview(), especially with calls from Android Webviews where setDomStorageEnabled has not been called (it is false by default).

Windvis commented 2 years ago

Sorry about that. I didn't know that disabling localStorage was a thing 😄. Should be fixed by #31 👍 .