Skip to content

Commit 628b3c2

Browse files
authored
Add Google Tag Manager support (#178)
1 parent 96fdcc5 commit 628b3c2

File tree

11 files changed

+135
-173
lines changed

11 files changed

+135
-173
lines changed

assets/js/ga.js

-139
This file was deleted.

assets/js/gtm.js

+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import {gtmCode, respectDoNotTrack} from '@params';
2+
3+
/**
4+
* Check if the Do Not Track setting is enabled.
5+
*
6+
* @returns {boolean}
7+
*/
8+
function isDoNotTrackEnabled() {
9+
if (typeof window === 'undefined') {
10+
return false;
11+
}
12+
const {doNotTrack, navigator} = window;
13+
14+
// Do Not Track Settings across browsers
15+
const dnt = (doNotTrack || navigator.doNotTrack || navigator.msDoNotTrack);
16+
17+
if (!dnt) {
18+
return false;
19+
}
20+
21+
return dnt === true ||
22+
dnt === 1 ||
23+
dnt === 'yes' ||
24+
(typeof dnt === 'string' && dnt.charAt(0) === '1');
25+
}
26+
27+
if (respectDoNotTrack && isDoNotTrackEnabled()) {
28+
// Skip analytics for users with Do Not Track enabled
29+
console.info('[TRACKING]: Respecting DNT with respect to analytics...'); // eslint-disable-line no-console
30+
} else {
31+
// Known DNT values not set, so we will assume it's off.
32+
if (gtmCode) {
33+
(function () {
34+
const baseUrl = 'https://www.googletagmanager.com';
35+
const params = new URLSearchParams({
36+
id: gtmCode,
37+
l: 'dataLayer'
38+
});
39+
40+
const script = document.createElement('script');
41+
script.src = `${baseUrl}/gtm.js?${params.toString()}`;
42+
script.type = 'text/javascript';
43+
script.async = true;
44+
45+
document.getElementsByTagName('head')[0].appendChild(script);
46+
47+
window.dataLayer = window.dataLayer || [];
48+
window.dataLayer.push({
49+
'gtm.start': new Date().getTime(),
50+
event: 'gtm.js'
51+
});
52+
}());
53+
}
54+
}

exampleSite/config/_default/config.yaml

-9
Original file line numberDiff line numberDiff line change
@@ -24,15 +24,6 @@ disableKinds:
2424
taxonomies:
2525
tag: tags
2626

27-
# Google Analytics Tracking ID.
28-
#
29-
# For more info, read the article
30-
# https://support.google.com/analytics/answer/10089681
31-
#
32-
# Set `HUGO_ENV` environment variable or `site.Params.env` configuration
33-
# parameter to "production" to use Google Analytics.
34-
googleAnalytics: ''
35-
3627
minify:
3728
# Do not minify XML files to avoid CDATA escape issues
3829
disableXML: true

exampleSite/config/_default/params.yaml

+9
Original file line numberDiff line numberDiff line change
@@ -141,3 +141,12 @@ comments:
141141
emitMetadata: 0
142142
inputPosition: bottom
143143
lang: en
144+
145+
privacy:
146+
googleTagManager:
147+
disable: true
148+
respectDoNotTrack: true
149+
150+
services:
151+
googleTagManager:
152+
id: ''

layouts/partials/head.html

+1-1
Original file line numberDiff line numberDiff line change
@@ -37,5 +37,5 @@
3737

3838
{{- /* Scripts */}}
3939
{{- partial "partials/scripts.html" . }}
40-
{{- partial "partials/seo/ga.html" . }}
40+
{{- partial "partials/head/analytics.html" . }}
4141
</head>

layouts/partials/head/analytics.html

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
{{- if eq hugo.Environment "production" }}
2+
{{- if not site.Params.Privacy.GoogleTagManager.Disable }}{{/* First check GTM */}}
3+
{{- with site.Params.Services.GoogleTagManager }}
4+
{{- $gtmParams := dict "gtmCode" (.ID) -}}
5+
{{- $gtmParams = merge $gtmParams (dict "respectDoNotTrack" site.Params.Privacy.GoogleTagManager.RespectDoNotTrack | default true) }}
6+
7+
{{- $gtmScript := slice -}}
8+
{{- $gtmScript = $gtmScript | append (resources.Get "js/gtm.js") -}}
9+
{{- $gtmScript = $gtmScript | resources.Concat "js/analytics.js" -}}
10+
{{- $gtmScript = $gtmScript | js.Build (dict "format" "iife" "target" "es2015" "minify" true "params" $gtmParams) -}}
11+
12+
{{- if site.Params.assets.disable_fingerprinting }}
13+
<script src="{{ $gtmScript.RelPermalink }}"></script>
14+
{{- else -}}
15+
{{- $gtmScript = $gtmScript | fingerprint -}}
16+
<script src="{{ $gtmScript.RelPermalink }}" integrity="{{ $gtmScript.Data.Integrity }}" crossorigin="anonymous"></script>
17+
{{- end -}}
18+
{{- end -}}
19+
{{ else }}{{/* If GTM is disabled delegate the rest to Hugo */}}
20+
{{ template "_internal/google_analytics.html" . }}
21+
{{ end }}
22+
{{ end }}

layouts/partials/seo/ga.html

-18
This file was deleted.

netlify-production.js

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
const fs = require('fs');
2+
const yaml = require('yaml');
3+
4+
const filePath = 'exampleSite/config/_default/params.yaml';
5+
const file = fs.readFileSync(filePath, 'utf8');
6+
const config = yaml.parse(file);
7+
8+
config.privacy.googleTagManager.disable = false;
9+
config.services.googleTagManager.id = 'GTM-W8D5W642';
10+
11+
const newYaml = yaml.stringify(config);
12+
13+
fs.writeFileSync(filePath, newYaml, 'utf8');
14+
15+
console.log('Updated config.yaml successfully!');

netlify.toml

+7-4
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
# a base has not been set. This sample publishes the directory
88
# located at the absolute path "root/project/build-output"
99
publish = 'public'
10+
command = 'npm install'
1011

1112
[build.environment]
1213
HUGO_VERSION = '0.121.0'
@@ -15,22 +16,24 @@
1516
# Production context: all deploys from the Production branch
1617
# set in your site’s Branches settings in the UI will inherit
1718
# these settings. You can define environment variables
18-
# here but we recommend using the Netlify UI for sensitive
19+
# here, but we recommend using the Netlify UI for sensitive
1920
# values to keep them out of your source repository.
2021
[context.production]
2122
command = 'hugo --source=exampleSite --baseURL ${URL} --destination ../public --minify'
2223

2324
[context.production.environment]
2425
HUGO_ENV = 'production'
25-
HUGO_GOOGLEANALYTICS = 'G-DP9Q137C3X'
26+
HUGO_ENABLEGITINFO = 'true'
2627

2728
# Deploy Preview context: all deploys generated from
2829
# a pull/merge request will inherit these settings.
2930
[context.deploy-preview]
30-
command = 'npm run netlify-preview; hugo --source=exampleSite --buildDrafts --buildFuture --baseURL ${DEPLOY_PRIME_URL} --destination ../public --minify'
31+
# command = 'npm run netlify-preview; hugo --source=exampleSite --buildDrafts --buildFuture --baseURL ${DEPLOY_PRIME_URL} --destination ../public --minify'
32+
command = 'npm run netlify-production; npm run netlify-preview; hugo --source=exampleSite --buildDrafts --buildFuture --baseURL ${DEPLOY_PRIME_URL} --destination ../public; cat ./public/index.html'
3133

3234
[context.deploy-preview.environment]
33-
HUGO_ENV = 'development'
35+
# HUGO_ENV = 'development'
36+
HUGO_ENV = 'production'
3437

3538
# Branch Deploy context: all deploys that are not from
3639
# a pull/merge request or from the Production branch

package-lock.json

+23-1
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

+4-1
Original file line numberDiff line numberDiff line change
@@ -23,12 +23,15 @@
2323
"server": "HUGO_RESOURCEDIR='../resources' HUGO_ENV=development hugo server --logLevel info --source=exampleSite --buildDrafts --buildFuture --ignoreCache --disableFastRender",
2424
"test": "playwright test",
2525
"lint": "eslint static/js/* assets/js/* tests/*.spec.js eslint.config.js playwright.config.js netlify-preview.js",
26+
"netlify-production": "node netlify-production.js",
2627
"netlify-preview": "node netlify-preview.js"
2728
},
2829
"devDependencies": {
2930
"@playwright/test": "^1.47.2",
3031
"@types/node": "^22.7.3",
3132
"eslint": "^9.11.1",
32-
"jsdom": "^25.0.1"
33+
"fs": "^0.0.1-security",
34+
"jsdom": "^25.0.1",
35+
"yaml": "^2.5.1"
3336
}
3437
}

0 commit comments

Comments
 (0)