Skip to content
Closed
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
25 changes: 14 additions & 11 deletions packages/ga4/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -345,22 +345,25 @@ function bindEvents(trackingId: string) {
function track(trackingId: string, props?: IProps);
function track(props?: IProps);
function track(...args: any[]) {
const [trackingId, { type, event, debug }] = getArguments(args);
try {
const [trackingId, { type, event, debug }] = getArguments(args);

if (!trackingId) {
console.error('GA4: Tracking ID is missing or undefined');
if (!trackingId) {
console.error('GA4: Tracking ID is missing or undefined');
return;
}

return;
}
const queryParams = getQueryParams(trackingId, { type, event, debug });
const endpoint = window.minimalAnalytics?.analyticsEndpoint || analyticsEndpoint;

const queryParams = getQueryParams(trackingId, { type, event, debug });
const endpoint = window.minimalAnalytics?.analyticsEndpoint || analyticsEndpoint;
navigator.sendBeacon(`${endpoint}?${queryParams}`);

navigator.sendBeacon(`${endpoint}?${queryParams}`);
bindEvents(trackingId);

bindEvents(trackingId);

trackCalled = true;
trackCalled = true;
} catch (error) {
console.error('GA4: ', error);
}
}

/* -----------------------------------
Expand Down
13 changes: 13 additions & 0 deletions packages/ga4/tests/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,19 @@ describe('ga4 -> track()', () => {
expect(navigator.sendBeacon).not.toBeCalled();
});

it("doesn't ppopagate exceptions", () => {
const errorLogMock = jest.spyOn(console, 'error');
const testError = new Error('test error');

jest.spyOn(navigator, 'sendBeacon').mockImplementation(() => {
throw testError;
});

expect(() => track(trackingId)).not.toThrow();

expect(errorLogMock).toHaveBeenCalledWith('GA4: ', testError);
});

it('can be called directly with a tracking ID', () => {
track(trackingId);

Expand Down