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);