plausible-tracker icon indicating copy to clipboard operation
plausible-tracker copied to clipboard

Check for localStorage support

Open elzii opened this issue 2 years ago • 3 comments

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

  • [x] Bug fix (non-breaking change which fixes an issue)
  • [x] New feature (non-breaking change which adds functionality)
  • [ ] Breaking change (fix or feature that would cause existing functionality to change)

Checklist:

  • [x] My code follows the code style of this project.
  • [ ] My change requires a change to the documentation.
  • [ ] I have updated the documentation accordingly.
  • [x] I have read the CONTRIBUTING document.
  • [x] I have added tests to cover my changes.
  • [x] All new and existing tests passed.

elzii avatar Apr 01 '22 18:04 elzii

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

elzii avatar Apr 01 '22 20:04 elzii

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?

ukutaht avatar Apr 04 '22 08:04 ukutaht

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

elzii avatar Apr 21 '22 21:04 elzii