Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Don't access localStorage if it is not available #31

Merged
merged 1 commit into from
Jun 6, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions src/lib/request.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,20 @@ describe('sendEvent', () => {

window.localStorage.removeItem('plausible_ignore');
});
test('does not throw an error if localStorage is not available', () => {
const localStorage = window.localStorage;
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
delete window['localStorage'];

expect(xmr).not.toHaveBeenCalled();
sendEvent('myEvent', defaultData);
expect(xmr).toHaveBeenCalled();

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
window.localStorage = localStorage;
});
test('calls callback', () => {
expect(xmr).not.toHaveBeenCalled();
const callback = jest.fn();
Expand Down
5 changes: 5 additions & 0 deletions src/lib/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,13 @@ export function sendEvent(
);
}

const canAccessLocalStorage =
typeof window.localStorage?.getItem === 'function';

const shouldIgnoreCurrentBrowser =
canAccessLocalStorage &&
localStorage.getItem('plausible_ignore') === 'true';

if (shouldIgnoreCurrentBrowser) {
return console.warn(
'[Plausible] Ignoring event because "plausible_ignore" is set to "true" in localStorage'
Expand Down