plausible / plausible-tracker

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

Check for localStorage support #26

Open elzii opened 2 years ago

elzii commented 2 years ago

Adds a function called checkLocalStorageSupport before invoking localStorage.getItem

Description

In some environments, for example: Figma plugins that are entirely inlined data:uri blobs, localStorage is not useable on the parent frame/window object. This first checks support, and allows plausible tracker to be used in some non-traditional contexts.

Should not introduce any breaking changes. Two unit tests are added as well.

Types of changes

Checklist:

elzii commented 2 years ago

This should probably be pulled out of sendEvent scope and only checked once on instantiation. Larger refactor that I can commit, but want to get author's eyes on this first as proof of concept and understanding the reasoning behind.

Example of error thrown on invoking plausible presently without this check: image

ukutaht commented 2 years ago

Thanks!

The solution we went with in the main codebase is using try-catch when attempting to read from localStorage: https://github.com/plausible/analytics/blob/d40faf6ec796eee23fcd8525d5b96d7623a05702/tracker/src/plausible.js#L38

What I like about this approach is the brevity of it. We try to keep all of our JS as lightweight as possible and the try catch doesn't add much weight.

What do you think about using a similar approach here?

elzii commented 2 years ago

even more elegant. i like it! thanks for adding. you just opened up plausible to all Figma plugins FYI by doing so :)