Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Google Tag Manager support #178

Merged
merged 12 commits into from
Sep 27, 2024
139 changes: 0 additions & 139 deletions assets/js/ga.js

This file was deleted.

54 changes: 54 additions & 0 deletions assets/js/gtm.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import {gtmCode, respectDoNotTrack} from '@params';

/**
* Check if the Do Not Track setting is enabled.
*
* @returns {boolean}
*/
function isDoNotTrackEnabled() {
if (typeof window === 'undefined') {
return false;
}
const {doNotTrack, navigator} = window;

// Do Not Track Settings across browsers
const dnt = (doNotTrack || navigator.doNotTrack || navigator.msDoNotTrack);

if (!dnt) {
return false;
}

return dnt === true ||
dnt === 1 ||
dnt === 'yes' ||
(typeof dnt === 'string' && dnt.charAt(0) === '1');
}

if (respectDoNotTrack && isDoNotTrackEnabled()) {
// Skip analytics for users with Do Not Track enabled
console.info('[TRACKING]: Respecting DNT with respect to analytics...'); // eslint-disable-line no-console
} else {
// Known DNT values not set, so we will assume it's off.
if (gtmCode) {
(function () {
const baseUrl = 'https://www.googletagmanager.com';
const params = new URLSearchParams({
id: gtmCode,
l: 'dataLayer'
});

const script = document.createElement('script');
script.src = `${baseUrl}/gtm.js?${params.toString()}`;
script.type = 'text/javascript';
script.async = true;

document.getElementsByTagName('head')[0].appendChild(script);

window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
'gtm.start': new Date().getTime(),
event: 'gtm.js'
});
}());
}
}
9 changes: 0 additions & 9 deletions exampleSite/config/_default/config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,6 @@ disableKinds:
taxonomies:
tag: tags

# Google Analytics Tracking ID.
#
# For more info, read the article
# https://support.google.com/analytics/answer/10089681
#
# Set `HUGO_ENV` environment variable or `site.Params.env` configuration
# parameter to "production" to use Google Analytics.
googleAnalytics: ''

minify:
# Do not minify XML files to avoid CDATA escape issues
disableXML: true
Expand Down
9 changes: 9 additions & 0 deletions exampleSite/config/_default/params.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -141,3 +141,12 @@ comments:
emitMetadata: 0
inputPosition: bottom
lang: en

privacy:
googleTagManager:
disable: true
respectDoNotTrack: true

services:
googleTagManager:
id: ''
2 changes: 1 addition & 1 deletion layouts/partials/head.html
Original file line number Diff line number Diff line change
Expand Up @@ -37,5 +37,5 @@

{{- /* Scripts */}}
{{- partial "partials/scripts.html" . }}
{{- partial "partials/seo/ga.html" . }}
{{- partial "partials/head/analytics.html" . }}
</head>
22 changes: 22 additions & 0 deletions layouts/partials/head/analytics.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{{- if eq hugo.Environment "production" }}
{{- if not site.Params.Privacy.GoogleTagManager.Disable }}{{/* First check GTM */}}
{{- with site.Params.Services.GoogleTagManager }}
{{- $gtmParams := dict "gtmCode" (.ID) -}}
{{- $gtmParams = merge $gtmParams (dict "respectDoNotTrack" site.Params.Privacy.GoogleTagManager.RespectDoNotTrack | default true) }}

{{- $gtmScript := slice -}}
{{- $gtmScript = $gtmScript | append (resources.Get "js/gtm.js") -}}
{{- $gtmScript = $gtmScript | resources.Concat "js/analytics.js" -}}
{{- $gtmScript = $gtmScript | js.Build (dict "format" "iife" "target" "es2015" "minify" true "params" $gtmParams) -}}

{{- if site.Params.assets.disable_fingerprinting }}
<script src="{{ $gtmScript.RelPermalink }}"></script>
{{- else -}}
{{- $gtmScript = $gtmScript | fingerprint -}}
<script src="{{ $gtmScript.RelPermalink }}" integrity="{{ $gtmScript.Data.Integrity }}" crossorigin="anonymous"></script>
{{- end -}}
{{- end -}}
{{ else }}{{/* If GTM is disabled delegate the rest to Hugo */}}
{{ template "_internal/google_analytics.html" . }}
{{ end }}
{{ end }}
18 changes: 0 additions & 18 deletions layouts/partials/seo/ga.html

This file was deleted.

15 changes: 15 additions & 0 deletions netlify-production.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const fs = require('fs');
const yaml = require('yaml');

const filePath = 'exampleSite/config/_default/params.yaml';
const file = fs.readFileSync(filePath, 'utf8');
const config = yaml.parse(file);

config.privacy.googleTagManager.disable = false;
config.services.googleTagManager.id = 'GTM-W8D5W642';

const newYaml = yaml.stringify(config);

fs.writeFileSync(filePath, newYaml, 'utf8');

console.log('Updated config.yaml successfully!');
11 changes: 7 additions & 4 deletions netlify.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
# a base has not been set. This sample publishes the directory
# located at the absolute path "root/project/build-output"
publish = 'public'
command = 'npm install'

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

[context.production.environment]
HUGO_ENV = 'production'
HUGO_GOOGLEANALYTICS = 'G-DP9Q137C3X'
HUGO_ENABLEGITINFO = 'true'

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

[context.deploy-preview.environment]
HUGO_ENV = 'development'
# HUGO_ENV = 'development'
HUGO_ENV = 'production'

# Branch Deploy context: all deploys that are not from
# a pull/merge request or from the Production branch
Expand Down
24 changes: 23 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,15 @@
"server": "HUGO_RESOURCEDIR='../resources' HUGO_ENV=development hugo server --logLevel info --source=exampleSite --buildDrafts --buildFuture --ignoreCache --disableFastRender",
"test": "playwright test",
"lint": "eslint static/js/* assets/js/* tests/*.spec.js eslint.config.js playwright.config.js netlify-preview.js",
"netlify-production": "node netlify-production.js",
"netlify-preview": "node netlify-preview.js"
},
"devDependencies": {
"@playwright/test": "^1.47.2",
"@types/node": "^22.7.3",
"eslint": "^9.11.1",
"jsdom": "^25.0.1"
"fs": "^0.0.1-security",
"jsdom": "^25.0.1",
"yaml": "^2.5.1"
}
}