Skip to content

Commit c1f0bbf

Browse files
authored
fix(gatsby-plugin-google-gtag): Add plugin options (#37953)
* add plugin options * change object syntax * update source code * update README * Restore packages/gatsby-plugin-google-gtag/src/gatsby-browser.js * Restore packages/gatsby-plugin-google-gtag/src/gatsby-ssr.js
1 parent 2dbd95d commit c1f0bbf

File tree

4 files changed

+162
-48
lines changed

4 files changed

+162
-48
lines changed

Diff for: packages/gatsby-plugin-google-gtag/README.md

+48-47
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ For more general information on gtag you can read Google's official documentatio
1010

1111
If you're migrating from analytics.js (gatsby-plugin-google-analytics) you can read about the subtle API differences in more depth at: https://developers.google.com/analytics/devguides/migration/ua/analyticsjs-to-gtagjs.
1212

13-
**Please note:** This plugin only works in production mode! To test your Global Site Tag is installed and firing events correctly run: `gatsby build && gatsby serve.`
13+
**Please note:** This plugin only works in production mode! To test that your Global Site Tag is installed and firing events correctly run: `gatsby build && gatsby serve.`
1414

1515
## Install
1616

@@ -20,8 +20,9 @@ npm install gatsby-plugin-google-gtag
2020

2121
## How to use
2222

23-
```js
24-
// In your gatsby-config.js
23+
The `trackingIds` option is **required** for this plugin to work correctly.
24+
25+
```js:title=gatsby-config.js
2526
module.exports = {
2627
plugins: [
2728
{
@@ -59,6 +60,50 @@ module.exports = {
5960
}
6061
```
6162

63+
### `gtagConfig.anonymize_ip` option
64+
65+
Some countries (such as Germany) require you to use the
66+
[\_anonymizeIP](https://support.google.com/analytics/answer/2763052) function for
67+
Google Site Tag. Otherwise you are not allowed to use it. The option adds the
68+
block of code below:
69+
70+
```js
71+
function gaOptout() {
72+
;(document.cookie =
73+
disableStr + "=true; expires=Thu, 31 Dec 2099 23:59:59 UTC;path=/"),
74+
(window[disableStr] = !0)
75+
}
76+
77+
var gaProperty = "UA-XXXXXXXX-X",
78+
disableStr = "ga-disable-" + gaProperty
79+
document.cookie.indexOf(disableStr + "=true") > -1 && (window[disableStr] = !0)
80+
```
81+
82+
If your visitors should be able to set an Opt-Out-Cookie (No future tracking)
83+
you can set a link e.g. in your imprint as follows:
84+
85+
`<a href="javascript:gaOptout();">Deactivate Google Tracking</a>`
86+
87+
### `gtagConfig.optimize_id` option
88+
89+
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.
90+
91+
### Other `gtagConfig` options
92+
93+
The `gtagConfig` is passed directly to the gtag config command, so you can specify everything it supports, e.g. `gtagConfig.cookie_name`, `gtagConfig.sample_rate`. If you're migrating from the analytics.js plugin, this means that all Create Only Fields should be snake_cased.
94+
95+
### `pluginConfig.respectDNT` option
96+
97+
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.
98+
99+
### `pluginConfig.exclude` option
100+
101+
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.
102+
103+
### `pluginConfig.delayOnRouteUpdate` option
104+
105+
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.
106+
62107
## Custom Events
63108

64109
This plugin automatically sends a "pageview" event to all products given as "trackingIds" on every Gatsbys route change.
@@ -99,47 +144,3 @@ export default () => (
99144
</div>
100145
)
101146
```
102-
103-
## The "gtagConfig.anonymize_ip" option
104-
105-
Some countries (such as Germany) require you to use the
106-
[\_anonymizeIP](https://support.google.com/analytics/answer/2763052) function for
107-
Google Site Tag. Otherwise you are not allowed to use it. The option adds the
108-
block of code below:
109-
110-
```js
111-
function gaOptout() {
112-
;(document.cookie =
113-
disableStr + "=true; expires=Thu, 31 Dec 2099 23:59:59 UTC;path=/"),
114-
(window[disableStr] = !0)
115-
}
116-
117-
var gaProperty = "UA-XXXXXXXX-X",
118-
disableStr = "ga-disable-" + gaProperty
119-
document.cookie.indexOf(disableStr + "=true") > -1 && (window[disableStr] = !0)
120-
```
121-
122-
If your visitors should be able to set an Opt-Out-Cookie (No future tracking)
123-
you can set a link e.g. in your imprint as follows:
124-
125-
`<a href="javascript:gaOptout();">Deactivate Google Tracking</a>`
126-
127-
## The "gtagConfig.optimize_id" option
128-
129-
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.
130-
131-
## Other "gtagConfig" options
132-
133-
The `gtagConfig` is passed directly to the gtag config command, so you can specify everything it supports, e.g. `gtagConfig.cookie_name`, `gtagConfig.sample_rate`. If you're migrating from the analytics.js plugin, this means that all Create Only Fields should be snake_cased.
134-
135-
## The "pluginConfig.respectDNT" option
136-
137-
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.
138-
139-
## The "pluginConfig.exclude" option
140-
141-
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.
142-
143-
## The "pluginConfig.delayOnRouteUpdate" option
144-
145-
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.

Diff for: packages/gatsby-plugin-google-gtag/package.json

+2-1
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,8 @@
1414
"@babel/cli": "^7.20.7",
1515
"@babel/core": "^7.20.12",
1616
"babel-preset-gatsby-package": "^3.9.0-next.0",
17-
"cross-env": "^7.0.3"
17+
"cross-env": "^7.0.3",
18+
"gatsby-plugin-utils": "^4.9.0-next.1"
1819
},
1920
"homepage": "https://github.com/gatsbyjs/gatsby/tree/master/packages/gatsby-plugin-google-gtag#readme",
2021
"keywords": [
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
import { testPluginOptionsSchema } from "gatsby-plugin-utils"
2+
import { pluginOptionsSchema } from "../gatsby-node"
3+
4+
describe(`pluginOptionsSchema`, () => {
5+
it(`should invalidate incorrect options`, async () => {
6+
const options = {
7+
trackingIds: undefined, // Is required
8+
gtagConfig: `test`,
9+
pluginConfig: {
10+
head: `test`,
11+
respectDNT: `test`,
12+
exclude: `test`,
13+
origin: 1,
14+
delayOnRouteUpdate: `test`,
15+
},
16+
}
17+
const expectedErrors = [
18+
`"trackingIds" is required`,
19+
`"gtagConfig" must be of type object`,
20+
`"pluginConfig.head" must be a boolean`,
21+
`"pluginConfig.respectDNT" must be a boolean`,
22+
`"pluginConfig.exclude" must be an array`,
23+
`"pluginConfig.origin" must be a string`,
24+
`"pluginConfig.delayOnRouteUpdate" must be a number`,
25+
]
26+
27+
const { isValid, errors } = await testPluginOptionsSchema(
28+
pluginOptionsSchema,
29+
options
30+
)
31+
32+
expect(isValid).toBe(false)
33+
expect(errors).toEqual(expectedErrors)
34+
})
35+
36+
it(`should validate correct options`, async () => {
37+
const options = {
38+
trackingIds: [`test`],
39+
gtagConfig: {
40+
anonymize_ip: true,
41+
},
42+
pluginConfig: {
43+
head: true,
44+
respectDNT: true,
45+
exclude: [`test`],
46+
origin: `test`,
47+
delayOnRouteUpdate: 1,
48+
},
49+
}
50+
const { isValid, errors } = await testPluginOptionsSchema(
51+
pluginOptionsSchema,
52+
options
53+
)
54+
55+
expect(isValid).toBe(true)
56+
expect(errors).toEqual([])
57+
})
58+
})
+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
// @ts-check
2+
3+
/**
4+
* @type {import('gatsby').GatsbyNode["pluginOptionsSchema"]}
5+
*/
6+
exports.pluginOptionsSchema = ({ Joi }) =>
7+
Joi.object({
8+
trackingIds: Joi.array()
9+
.items(Joi.string())
10+
.description(
11+
`The tracking IDs; the tracking code won't be generated without them.`
12+
)
13+
.required(),
14+
gtagConfig: Joi.object()
15+
.keys({
16+
optimize_id: Joi.string().description(
17+
`Enable if you need to use Google Optimize.`
18+
),
19+
anonymize_ip: Joi.boolean()
20+
.description(`Enable if you need to use the "anonymizeIP" function.`)
21+
.default(false),
22+
})
23+
.unknown(true)
24+
.description(
25+
`This object gets passed directly to the gtag config command.`
26+
)
27+
.default({}),
28+
pluginConfig: Joi.object()
29+
.keys({
30+
head: Joi.boolean()
31+
.description(
32+
`Puts tracking script in the <head> instead of the <body>`
33+
)
34+
.default(false),
35+
respectDNT: Joi.boolean()
36+
.description(
37+
`If you enable this optional option, Google Global Site Tag will not be loaded at all for visitors that have "Do Not Track" enabled.`
38+
)
39+
.default(false),
40+
exclude: Joi.array()
41+
.items(Joi.string())
42+
.description(
43+
`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.`
44+
)
45+
.default([]),
46+
origin: Joi.string()
47+
.description(`Your optional self hosted origin for the script.`)
48+
.default(`https://www.googletagmanager.com`),
49+
delayOnRouteUpdate: Joi.number()
50+
.description(`Delay processing pageview events on route update`)
51+
.default(0),
52+
})
53+
.description(`Configure the plugin's behavior.`),
54+
})

0 commit comments

Comments
 (0)