Skip to content
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
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ const TEST_GA_ID = 'G-TEST12345'
const analyticsWindow = window as AnalyticsWindow

/** Returns the recorded gtag command tuples pushed onto the dataLayer. */
const commands = (): unknown[][] => (analyticsWindow.dataLayer ?? []) as unknown[][]
const commands = (): unknown[][] =>
(analyticsWindow.dataLayer ?? []).map((entry) => Array.from(entry as ArrayLike<unknown>))

/** Finds the first recorded command matching the given leading arguments. */
const findCommand = (...prefix: unknown[]): unknown[] | undefined =>
Expand All @@ -44,6 +45,9 @@ describe('ensureGtag', () => {

gtag?.('event', 'page_view')

expect(Object.prototype.toString.call(analyticsWindow.dataLayer?.[0])).toBe(
'[object Arguments]'
)
expect(commands()).toEqual([['event', 'page_view']])
})

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,13 @@ export function ensureGtag(): GtagFn | undefined {
analyticsWindow.dataLayer = analyticsWindow.dataLayer || []
analyticsWindow.gtag =
analyticsWindow.gtag ||
((...args: unknown[]) => {
analyticsWindow.dataLayer?.push(args)
})
function gtag() {
// GA's gtag.js only treats an entry as a command when it is a genuine
// `arguments` object; pushing a plain array makes it ignore commands like
// `config`/`consent`, so we intentionally forward `arguments` here.
// eslint-disable-next-line prefer-rest-params
analyticsWindow.dataLayer?.push(arguments)
}

return analyticsWindow.gtag
}
Expand Down