Skip to content
This repository has been archived by the owner on Nov 10, 2023. It is now read-only.

Commit

Permalink
Refactor: use the track function in the pageView hook (#3975)
Browse files Browse the repository at this point in the history
  • Loading branch information
katspaugh authored Jun 17, 2022
1 parent 45a806e commit 5cc06e9
Showing 1 changed file with 28 additions and 19 deletions.
47 changes: 28 additions & 19 deletions src/utils/googleTagManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ export const loadGoogleTagManager = (): void => {
return
}

const page_path = getAnonymizedPathname()
const pagePath = getAnonymizedPathname()

TagManager.initialize({
gtmId: GOOGLE_TAG_MANAGER_ID,
Expand All @@ -89,8 +89,8 @@ export const loadGoogleTagManager = (): void => {
// Must emit (custom) event in order to trigger page tracking
event: GTM_EVENT.PAGEVIEW,
chainId: _getChainId(),
pageLocation: `${location.origin}${page_path}`,
pagePath: page_path,
pageLocation: `${location.origin}${pagePath}`,
pagePath,
// Block JS variables and custom scripts
// @see https://developers.google.com/tag-platform/tag-manager/web/restrict
'gtm.blocklist': ['j', 'jsm', 'customScripts'],
Expand All @@ -112,6 +112,16 @@ export const unloadGoogleTagManager = (): void => {
removeCookies(GOOGLE_ANALYTICS_COOKIE_LIST)
}

type PageViewDataLayer = {
event: GTM_EVENT
chainId: string
pageLocation: string
pagePath: string
eventCategory: undefined
eventAction: undefined
eventLabel: undefined
}

export const usePageTracking = (): void => {
const didMount = useRef(false)
const { pathname } = useLocation()
Expand All @@ -123,21 +133,20 @@ export const usePageTracking = (): void => {
return
}

const page_path = getAnonymizedPathname()

TagManager.dataLayer({
dataLayer: {
// Must emit (custom) event in order to trigger page tracking
event: GTM_EVENT.PAGEVIEW,
chainId,
pageLocation: `${location.origin}${page_path}`,
pagePath: page_path,
// Clear dataLayer
eventCategory: undefined,
eventAction: undefined,
eventLabel: undefined,
},
})
const pagePath = getAnonymizedPathname()

const event: PageViewDataLayer = {
// Must emit (custom) event in order to trigger page tracking
event: GTM_EVENT.PAGEVIEW,
chainId,
pageLocation: `${location.origin}${pagePath}`,
pagePath,
// Clear dataLayer
eventCategory: undefined,
eventAction: undefined,
eventLabel: undefined,
}
track(event)
}, [chainId, pathname])
}

Expand Down Expand Up @@ -226,7 +235,7 @@ export const trackSafeAppMessage = ({
track(dataLayer)
}

function track(dataLayer: EventDataLayer | SafeAppEventDataLayer) {
function track(dataLayer: EventDataLayer | SafeAppEventDataLayer | PageViewDataLayer) {
if (!IS_PRODUCTION) {
console.info('[GTM]', dataLayer)
}
Expand Down

0 comments on commit 5cc06e9

Please sign in to comment.