Skip to content

Commit

Permalink
feat(gatsby-plugin-google-gtag): Add delayOnRouteUpdate option (#37017
Browse files Browse the repository at this point in the history
)

Fixes #15504
  • Loading branch information
Simon-Tang authored Nov 17, 2022
1 parent 3032a1b commit c132f2d
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 4 deletions.
6 changes: 6 additions & 0 deletions packages/gatsby-plugin-google-gtag/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ module.exports = {
exclude: ["/preview/**", "/do-not-track/me/too/"],
// Defaults to https://www.googletagmanager.com
origin: "YOUR_SELF_HOSTED_ORIGIN",
// Delays processing pageview events on route update (in milliseconds)
delayOnRouteUpdate: 0,
},
},
},
Expand Down Expand Up @@ -137,3 +139,7 @@ If you enable this optional option, Google Global Site Tag will not be loaded at
## The "pluginConfig.exclude" option

If you need to exclude any path from the tracking system, you can add it (one or more) to this optional array as glob expressions.

## The "pluginConfig.delayOnRouteUpdate" option

If you need to delay processing pageview events on route update (e.g. to wait for page transitions with [`gatsby-plugin-transition-link`](https://www.gatsbyjs.com/plugins/gatsby-plugin-transition-link/)), then this option adds a delay before generating the pageview event.
12 changes: 8 additions & 4 deletions packages/gatsby-plugin-google-gtag/src/gatsby-browser.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
exports.onRouteUpdate = ({ location }) => {
exports.onRouteUpdate = ({ location }, pluginOptions = {}) => {
if (process.env.NODE_ENV !== `production` || typeof gtag !== `function`) {
return null
}

const pluginConfig = pluginOptions.pluginConfig || {}

const pathIsExcluded =
location &&
typeof window.excludeGtagPaths !== `undefined` &&
Expand All @@ -18,13 +20,15 @@ exports.onRouteUpdate = ({ location }) => {
window.gtag(`event`, `page_view`, { page_path: pagePath })
}

const { delayOnRouteUpdate = 0 } = pluginConfig

if (`requestAnimationFrame` in window) {
requestAnimationFrame(() => {
requestAnimationFrame(sendPageView)
requestAnimationFrame(() => setTimeout(sendPageView, delayOnRouteUpdate))
})
} else {
// simulate 2 rAF calls
setTimeout(sendPageView, 32)
// Delay by 32ms to simulate 2 requestOnAnimationFrame calls
setTimeout(sendPageView, 32 + delayOnRouteUpdate)
}

return null
Expand Down

0 comments on commit c132f2d

Please sign in to comment.