-
Notifications
You must be signed in to change notification settings - Fork 10.3k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add gatsby-plugin-google-gtag (#9032)
This PR adds support for Google's Global Site Tag (gtag) and closes #8341 you can view that issue for a detailed breakdown.
- Loading branch information
1 parent
6fed3e5
commit eadb0f3
Showing
8 changed files
with
344 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
{ | ||
"presets": [ | ||
["../../.babel-preset.js", { "browser": true }] | ||
] | ||
} | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
/*.js |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
# Logs | ||
logs | ||
*.log | ||
|
||
# Runtime data | ||
pids | ||
*.pid | ||
*.seed | ||
|
||
# Directory for instrumented libs generated by jscoverage/JSCover | ||
lib-cov | ||
|
||
# Coverage directory used by tools like istanbul | ||
coverage | ||
|
||
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) | ||
.grunt | ||
|
||
# node-waf configuration | ||
.lock-wscript | ||
|
||
# Compiled binary addons (http://nodejs.org/api/addons.html) | ||
build/Release | ||
|
||
# Dependency directory | ||
# https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git | ||
node_modules | ||
*.un~ | ||
yarn.lock | ||
src | ||
flow-typed | ||
coverage | ||
decls | ||
examples |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,122 @@ | ||
# gatsby-plugin-google-gtag | ||
|
||
Easily add Google Global Site Tag to your Gatsby site. | ||
|
||
## Install | ||
|
||
`npm install --save gatsby-plugin-google-gtag` | ||
|
||
## How to use | ||
|
||
```js | ||
// In your gatsby-config.js | ||
module.exports = { | ||
plugins: [ | ||
{ | ||
resolve: `gatsby-plugin-google-gtag`, | ||
options: { | ||
// You can add multiple tracking ids and a pageview event will be fired for all of them. | ||
trackingIds: [ | ||
'GA-TRACKING_ID', // Google Analytics / GA | ||
'AW-CONVERSION_ID', // Google Ads / Adwords / AW | ||
'DC-FLOODIGHT_ID', // Marketing Platform advertising products (Display & Video 360, Search Ads 360, and Campaign Manager) | ||
], | ||
// This object gets passed directly to the gtag config command | ||
// This config will be shared accross all trackingIds | ||
gtagConfig: { | ||
optimize_id: 'OPT_CONTAINER_ID', | ||
anonymize_ip: true, | ||
}, | ||
// This object is used for configuration specific to this plugin | ||
pluginConfig: { | ||
// Puts tracking script in the head instead of the body | ||
head: false, | ||
// Setting this parameter is also optional | ||
respectDNT: true, | ||
// Avoids sending pageview hits from custom paths | ||
exclude: ['/preview/**', '/do-not-track/me/too/'], | ||
}, | ||
}, | ||
}, | ||
], | ||
} | ||
``` | ||
|
||
## Custom Events | ||
|
||
This plugin automatically sends a "pageview" event to all products given as "trackingIds" on every Gatsbys route change. | ||
|
||
If you want to call a custom event you have access to `window.gtag` where you can call an event for all products: | ||
|
||
```js | ||
window.gtag('event', 'click', { ...data }); | ||
``` | ||
|
||
or you can target a specific product: | ||
|
||
```js | ||
window.gtag('event', 'click', { send_to: 'AW-CONVERSION_ID', ...data }); | ||
``` | ||
|
||
In either case don't forget to guard against SSR: | ||
|
||
```js | ||
typeof window !== 'undefined' && window.gtag('event', 'click', {...data); | ||
``` | ||
## `<OutboundLink>` component | ||
To make it easy to track clicks on outbound links the plugin provides a component. | ||
To use it, simply import it and use it like you would the `<a>` element e.g. | ||
```jsx | ||
import React from 'react'; | ||
import { OutboundLink } from 'gatsby-plugin-google-gtag' | ||
|
||
export default () => { | ||
<div> | ||
<OutboundLink | ||
href="https://www.gatsbyjs.org/packages/gatsby-plugin-google-gtag/" | ||
> | ||
Visit the Google Global Site Tag plugin page! | ||
</OutboundLink> | ||
</div> | ||
} | ||
``` | ||
## The "gtagConfig.anonymize_ip" option | ||
Some countries (such as Germany) require you to use the | ||
[\_anonymizeIP](https://support.google.com/analytics/answer/2763052) function for | ||
Google Site Tag. Otherwise you are not allowed to use it. The option adds the | ||
block of code below: | ||
```js | ||
function gaOptout() { | ||
;(document.cookie = | ||
disableStr + '=true; expires=Thu, 31 Dec 2099 23:59:59 UTC;path=/'), | ||
(window[disableStr] = !0) | ||
} | ||
|
||
var gaProperty = 'UA-XXXXXXXX-X', | ||
disableStr = 'ga-disable-' + gaProperty | ||
document.cookie.indexOf(disableStr + '=true') > -1 && (window[disableStr] = !0) | ||
``` | ||
If your visitors should be able to set an Opt-Out-Cookie (No future tracking) | ||
you can set a link e.g. in your imprint as follows: | ||
`<a href="javascript:gtagOptout();">Deactive Google Tracking</a>` | ||
## The "pluginConfig.respectDNT" option | ||
If you enable this optional option, Google Global Site Tag will not be loaded at all for visitors that have "Do Not Track" enabled. While using Google Global Site Tag does not necessarily constitute Tracking, you might still want to do this to cater to more privacy oriented users. | ||
## 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 "gtagConfig.optimize_id" option | ||
If you need to use Google Optimize for A/B testing, you can add this optional Optimize container id to allow Google Optimize to load the correct test parameters for your site. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
{ | ||
"name": "gatsby-plugin-google-gtag", | ||
"description": "Gatsby plugin to add google gtag onto a site", | ||
"version": "1.0.0-beta.0", | ||
"author": "Tyler Buchea <tyler@buchea.com>", | ||
"bugs": { | ||
"url": "https://github.com/gatsbyjs/gatsby/issues" | ||
}, | ||
"dependencies": { | ||
"@babel/runtime": "^7.0.0", | ||
"minimatch": "^3.0.4" | ||
}, | ||
"devDependencies": { | ||
"@babel/cli": "^7.0.0", | ||
"@babel/core": "^7.0.0", | ||
"cross-env": "^5.1.4" | ||
}, | ||
"homepage": "https://github.com/gatsbyjs/gatsby/tree/master/packages/gatsby-plugin-google-gtag#readme", | ||
"keywords": [ | ||
"gatsby", | ||
"gatsby-plugin", | ||
"google gtag", | ||
"google global site tag" | ||
], | ||
"license": "MIT", | ||
"main": "index.js", | ||
"peerDependencies": { | ||
"gatsby": ">2.0.0-alpha" | ||
}, | ||
"repository": "https://github.com/gatsbyjs/gatsby/tree/master/packages/gatsby-plugin-google-gtag", | ||
"scripts": { | ||
"build": "babel src --out-dir . --ignore **/__tests__", | ||
"prepare": "cross-env NODE_ENV=production npm run build", | ||
"watch": "babel -w src --out-dir . --ignore **/__tests__" | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
export const onRouteUpdate = function({ location }) { | ||
if (process.env.NODE_ENV !== `production` || typeof gtag !== `function`) { | ||
return null | ||
} | ||
|
||
const pathIsExcluded = | ||
location && | ||
typeof window.excludeGtagPaths !== `undefined` && | ||
window.excludeGtagPaths.some(rx => rx.test(location.pathname)) | ||
|
||
if (pathIsExcluded) return null | ||
|
||
const pagePath = location | ||
? location.pathname + location.search + location.hash | ||
: undefined | ||
window.gtag(`event`, `page_view`, { page_path: pagePath }) | ||
|
||
return null | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,71 @@ | ||
import React from "react" | ||
import { Minimatch } from "minimatch" | ||
|
||
export const onRenderBody = ( | ||
{ setHeadComponents, setPostBodyComponents }, | ||
pluginOptions | ||
) => { | ||
if (process.env.NODE_ENV !== `production`) return null | ||
|
||
const firstTrackingId = | ||
pluginOptions.trackingIds && pluginOptions.trackingIds.length | ||
? pluginOptions.trackingIds[0] | ||
: `` | ||
|
||
const excludeGtagPaths = [] | ||
if (typeof pluginOptions.pluginConfig.exclude !== `undefined`) { | ||
pluginOptions.pluginConfig.exclude.map(exclude => { | ||
const mm = new Minimatch(exclude) | ||
excludeGtagPaths.push(mm.makeRe()) | ||
}) | ||
} | ||
|
||
const setComponents = pluginOptions.pluginConfig.head | ||
? setHeadComponents | ||
: setPostBodyComponents | ||
|
||
const renderHtml = () => ` | ||
${ | ||
excludeGtagPaths.length | ||
? `window.excludeGtagPaths=[${excludeGtagPaths.join(`,`)}];` | ||
: `` | ||
} | ||
${ | ||
typeof pluginOptions.gtagConfig.anonymize_ip !== `undefined` && | ||
pluginOptions.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);` | ||
: `` | ||
} | ||
if(${ | ||
typeof pluginOptions.respectDNT !== `undefined` && | ||
pluginOptions.respectDNT === true | ||
? `!(navigator.doNotTrack == "1" || window.doNotTrack == "1")` | ||
: `true` | ||
}) { | ||
window.dataLayer = window.dataLayer || []; | ||
function gtag(){dataLayer.push(arguments);} | ||
gtag('js', new Date()); | ||
${pluginOptions.trackingIds | ||
.map( | ||
trackingId => | ||
`gtag('config', '${trackingId}', ${JSON.stringify( | ||
pluginOptions.gtagConfig || {} | ||
)});` | ||
) | ||
.join(``)} | ||
} | ||
` | ||
|
||
return setComponents([ | ||
<script | ||
key={`gatsby-plugin-google-gtag`} | ||
async | ||
src={`https://www.googletagmanager.com/gtag/js?id=${firstTrackingId}`} | ||
/>, | ||
<script | ||
key={`gatsby-plugin-google-gtag-config`} | ||
dangerouslySetInnerHTML={{ __html: renderHtml() }} | ||
/>, | ||
]) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
import React from "react" | ||
import PropTypes from "prop-types" | ||
|
||
function OutboundLink(props) { | ||
return ( | ||
<a | ||
{...props} | ||
onClick={e => { | ||
if (typeof props.onClick === `function`) { | ||
props.onClick() | ||
} | ||
let redirect = true | ||
if ( | ||
e.button !== 0 || | ||
e.altKey || | ||
e.ctrlKey || | ||
e.metaKey || | ||
e.shiftKey || | ||
e.defaultPrevented | ||
) { | ||
redirect = false | ||
} | ||
if (props.target && props.target.toLowerCase() !== `_self`) { | ||
redirect = false | ||
} | ||
if (window.gtag) { | ||
window.gtag(`event`, `click`, { | ||
event_category: `outbound`, | ||
event_label: props.href, | ||
transport_type: redirect ? `beacon` : ``, | ||
event_callback: function() { | ||
if (redirect) { | ||
document.location = props.href | ||
} | ||
}, | ||
}) | ||
} else { | ||
if (redirect) { | ||
document.location = props.href | ||
} | ||
} | ||
|
||
return false | ||
}} | ||
/> | ||
) | ||
} | ||
|
||
OutboundLink.propTypes = { | ||
href: PropTypes.string, | ||
target: PropTypes.string, | ||
onClick: PropTypes.func, | ||
} | ||
|
||
export { OutboundLink } |