From 8f17c5fdcd8fca4cdef1d4ca25006708ad3d48db Mon Sep 17 00:00:00 2001 From: Simon Kohlmeyer Date: Sun, 16 Mar 2025 18:42:29 +0100 Subject: [PATCH] fix(ga4): be robust against missing navigator.sendBeacon Closes #56 --- packages/ga4/src/index.ts | 4 ++++ packages/ga4/tests/index.test.ts | 18 ++++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/packages/ga4/src/index.ts b/packages/ga4/src/index.ts index 9f70da1..2d2aeb9 100644 --- a/packages/ga4/src/index.ts +++ b/packages/ga4/src/index.ts @@ -349,7 +349,11 @@ function track(...args: any[]) { if (!trackingId) { console.error('GA4: Tracking ID is missing or undefined'); + return; + } + if (!navigator.sendBeacon) { + console.warn('GA4: navigator.sendBeacon is not supported in this browser'); return; } diff --git a/packages/ga4/tests/index.test.ts b/packages/ga4/tests/index.test.ts index 5e0ee39..6e06f63 100644 --- a/packages/ga4/tests/index.test.ts +++ b/packages/ga4/tests/index.test.ts @@ -99,6 +99,24 @@ describe('ga4 -> track()', () => { expect(navigator.sendBeacon).not.toBeCalled(); }); + it.skip('logs an error message if sendBeacon is undefined', () => { + // It would be nice if we could test this, but sadly jest does not allow us to mock this + // property. + // + // Additionally, replaceProperty is only available in jest 29 and above, but since it doesn't + // work anyways we don't need this to force an upgrade. + // + // > Property `sendBeacon` is not declared configurable + + // @ts-ignore + jest.replaceProperty(navigator, 'sendBeacon', undefined); + + track(trackingId); + + expect(errorSpy).toHaveBeenCalledWith(errorTrackingId); + expect(navigator.sendBeacon).not.toBeCalled(); + }); + it('can be called directly with a tracking ID', () => { track(trackingId);