Skip to content

Commit

Permalink
fix(gatsby-plugin-google-gtag): disable default pageview tracking (ga…
Browse files Browse the repository at this point in the history
…tsbyjs#9842)

The default behavior of the `config` snippet is to send a pageview automatically; this is in contrast with the `exclude` option and the plugin tracks, on page load, even the excluded pages.

This PR solve also the double pageview hits on page load too: the first is made by the default behavior and the second one by the `onRouteUpdate` event.
  • Loading branch information
valse authored and gpetrioli committed Jan 22, 2019
1 parent c47e2ac commit c2f3480
Showing 1 changed file with 10 additions and 5 deletions.
15 changes: 10 additions & 5 deletions packages/gatsby-plugin-google-gtag/src/gatsby-ssr.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,13 @@ exports.onRenderBody = (
) => {
if (process.env.NODE_ENV !== `production`) return null

const gtagConfig = pluginOptions.gtagConfig || {}

// Prevent duplicate or excluded pageview events being emitted on initial load of page by the `config` command
// https://developers.google.com/analytics/devguides/collection/gtagjs/#disable_pageview_tracking

gtagConfig.send_page_view = false

const firstTrackingId =
pluginOptions.trackingIds && pluginOptions.trackingIds.length
? pluginOptions.trackingIds[0]
Expand All @@ -31,8 +38,8 @@ exports.onRenderBody = (
: ``
}
${
typeof pluginOptions.gtagConfig.anonymize_ip !== `undefined` &&
pluginOptions.gtagConfig.anonymize_ip === true
typeof gtagConfig.anonymize_ip !== `undefined` &&
gtagConfig.anonymize_ip === true
? `function gaOptout(){document.cookie=disableStr+'=true; expires=Thu, 31 Dec 2099 23:59:59 UTC;path=/',window[disableStr]=!0}var gaProperty='${firstTrackingId}',disableStr='ga-disable-'+gaProperty;document.cookie.indexOf(disableStr+'=true')>-1&&(window[disableStr]=!0);`
: ``
}
Expand All @@ -49,9 +56,7 @@ exports.onRenderBody = (
${pluginOptions.trackingIds
.map(
trackingId =>
`gtag('config', '${trackingId}', ${JSON.stringify(
pluginOptions.gtagConfig || {}
)});`
`gtag('config', '${trackingId}', ${JSON.stringify(gtagConfig)});`
)
.join(``)}
}
Expand Down

0 comments on commit c2f3480

Please sign in to comment.