Skip to content

Commit

Permalink
Insert Google Tag Manager snippet in template (#1811)
Browse files Browse the repository at this point in the history
https://eaflood.atlassian.net/browse/IWTF-3732

This PR adds the snippet for Google Tag Manager to the default layout. This snippet should only be inserted when the container ID is present.
  • Loading branch information
irisfaraway authored Nov 2, 2023
1 parent 6b7bc62 commit 1ff5e92
Show file tree
Hide file tree
Showing 9 changed files with 94 additions and 1 deletion.
1 change: 1 addition & 0 deletions docker/env/gafl_webapp.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ DEBUG=webapp:*

# Tracking
#ANALYTICS_PRIMARY_PROPERTY=G-DJMSHRPMW8 // this is the non-prod tracking update as required
#GTM_CONTAINER_ID=GTM-ABC1234

# Welsh language feature switch
SHOW_WELSH_CONTENT=true
Expand Down
22 changes: 22 additions & 0 deletions packages/gafl-webapp-service/src/__tests__/server.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,28 @@ describe('The server', () => {
expect(request.response.source.context._uri[element]).toEqual(expect.stringMatching(regexMatch))
})

describe('logGtmConfig', () => {
it('should log the gtmContainerId value if it is set', async () => {
const expectedId = 'GTM-ABC1234'
process.env.GTM_CONTAINER_ID = expectedId
const consoleLogSpy = jest.spyOn(console, 'log').mockImplementation(jest.fn())
createServer(catboxOptions)
await init()
expect(consoleLogSpy).toHaveBeenCalledWith(`gtmContainerId is set to ${expectedId}`)
await server.stop()
delete process.env.GTM_CONTAINER_ID
})

it('should log that gtmContainerId is not set if it is not set', async () => {
delete process.env.GTM_CONTAINER_ID
const consoleLogSpy = jest.spyOn(console, 'log').mockImplementation(jest.fn())
createServer(catboxOptions)
await init()
expect(consoleLogSpy).toHaveBeenCalledWith('gtmContainerId is not set')
await server.stop()
})
})

const getSampleRequest = (overrides = {}) => ({
auth: {},
method: 'get',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ exports[`The page handler function sets the value of pageData with displayAnalyt
"analyticsSelected": false,
"backRef": null,
"displayAnalytics": false,
"gtmContainerId": false,
"mssgs": undefined,
"pageLanguageSetToWelsh": false,
"uri": Object {
Expand Down Expand Up @@ -41,6 +42,7 @@ exports[`The page handler function sets the value of pageData with displayAnalyt
"analyticsSelected": false,
"backRef": null,
"displayAnalytics": true,
"gtmContainerId": false,
"mssgs": undefined,
"pageLanguageSetToWelsh": false,
"uri": Object {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,25 @@ describe('The page handler function', () => {
expect(toolkit.view).toMatchSnapshot()
})

it('sets the value of gtmContainerId to the GTM_CONTAINER_ID env var', async () => {
const expectedValue = 'expected'
process.env.GTM_CONTAINER_ID = expectedValue

const { get } = pageHandler('', 'view', '/next/page')
const toolkit = getMockToolkit()

await get(getMockRequest(), toolkit)

expect(toolkit.view).toHaveBeenCalledWith(
expect.any(String),
expect.objectContaining({
gtmContainerId: expectedValue
})
)

delete process.env.GTM_CONTAINER_ID
})

it.each([
['payment cancelled', PAYMENT_CANCELLED.uri],
['payment failed', PAYMENT_FAILED.uri],
Expand Down
1 change: 1 addition & 0 deletions packages/gafl-webapp-service/src/handlers/page-handler.js
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@ export default (path, view, completion, getData) => ({
pageData.analyticsMessageDisplayed = analytics ? analytics[ANALYTICS.seenMessage] : false
pageData.analyticsSelected = analytics ? analytics[ANALYTICS.selected] : false
pageData.acceptedTracking = analytics ? analytics[ANALYTICS.acceptTracking] : false
pageData.gtmContainerId = process.env.GTM_CONTAINER_ID || false

pageData.displayAnalytics = displayAnalytics(request)

Expand Down
13 changes: 12 additions & 1 deletion packages/gafl-webapp-service/src/pages/layout/layout.njk
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,11 @@
<meta http-equiv="Cache-Control" content="no-store" />
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="-1">
{% if gtmContainerId %}
<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src='https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);})(window,document,'script','dataLayer','{{gtmContainerId}}');</script>
<!-- End Google Tag Manager -->
{% endif %}
{% endblock %}

{% block header %}
Expand Down Expand Up @@ -170,7 +175,13 @@
{% endif %}
{% endblock %}

{% block bodyStart %}{% endblock %}
{% block bodyStart %}
{% if gtmContainerId %}
<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id={{gtmContainerId}}" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->
{% endif %}
{% endblock %}

{% set footerHtml %}
<div class="no-print">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,7 @@ describe('guidance page handlers', () => {

expect(mockToolkit.view).toHaveBeenCalledWith(uri.NEW_PRICES.page, {
altLang: ['that-locale'],
gtmContainerId: false,
mssgs: catalog,
uri: {
back: mockUri
Expand Down Expand Up @@ -262,6 +263,24 @@ describe('guidance page handlers', () => {
})
)
})

it('sets the value of gtmContainerId to the GTM_CONTAINER_ID env var', async () => {
const expectedValue = 'expected'
process.env.GTM_CONTAINER_ID = expectedValue

const toolkit = getMockToolkit()
const request = getMockRequest()
await pageHandler(request, toolkit)

expect(toolkit.view).toHaveBeenCalledWith(
expect.any(String),
expect.objectContaining({
gtmContainerId: expectedValue
})
)

delete process.env.GTM_CONTAINER_ID
})
})

const getMockRequest = (i18nValues, search = '') => {
Expand Down
8 changes: 8 additions & 0 deletions packages/gafl-webapp-service/src/routes/misc-routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,16 +26,20 @@ import { addLanguageCodeToUri } from '../processors/uri-helper.js'
import analytics from '../handlers/analytics-handler.js'
import { welshEnabledAndApplied } from '../processors/page-language-helper.js'

const gtmContainerIdOrNull = () => process.env.GTM_CONTAINER_ID || false

const simpleView = view => ({
method: 'GET',
path: view.uri,
handler: async (request, h) => {
const mssgs = request.i18n.getCatalog()
const altLang = request.i18n.getLocales().filter(locale => locale !== request.i18n.getLocale())
const gtmContainerId = gtmContainerIdOrNull()
const pageLanguageSetToWelsh = welshEnabledAndApplied(request)
return h.view(view.page, {
mssgs,
altLang,
gtmContainerId,
pageLanguageSetToWelsh,
uri: {
back: addLanguageCodeToUri(request, CONTROLLER.uri)
Expand Down Expand Up @@ -95,10 +99,12 @@ export default [
path: COOKIES.uri,
handler: async (request, h) => {
const altLang = request.i18n.getLocales().filter(locale => locale !== request.i18n.getLocale())
const gtmContainerId = gtmContainerIdOrNull()
const pageLanguageSetToWelsh = welshEnabledAndApplied(request)

return h.view(COOKIES.page, {
altLang,
gtmContainerId,
pageLanguageSetToWelsh,
mssgs: request.i18n.getCatalog(),
cookie: {
Expand All @@ -118,10 +124,12 @@ export default [
path: NEW_PRICES.uri,
handler: async (request, h) => {
const altLang = request.i18n.getLocales().filter(locale => locale !== request.i18n.getLocale())
const gtmContainerId = gtmContainerIdOrNull()
const pageLanguageSetToWelsh = welshEnabledAndApplied(request)

return h.view(NEW_PRICES.page, {
altLang,
gtmContainerId,
pageLanguageSetToWelsh,
mssgs: request.i18n.getCatalog(),
uri: {
Expand Down
10 changes: 10 additions & 0 deletions packages/gafl-webapp-service/src/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,14 @@ const addDefaultHeaders = (request, h) => {
return h.continue
}

const logGtmConfig = gtmContainerId => {
if (gtmContainerId) {
console.log(`gtmContainerId is set to ${gtmContainerId}`)
} else {
console.log('gtmContainerId is not set')
}
}

const init = async () => {
await server.register(getPlugins())
const viewPaths = [...new Set(find.fileSync(/\.njk$/, path.join(Dirname, './src/pages')).map(f => path.dirname(f)))]
Expand Down Expand Up @@ -194,6 +202,8 @@ const init = async () => {
server.route(routes)
await server.start()

logGtmConfig(process.env.GTM_CONTAINER_ID)

console.log('Server running on %s', server.info.uri)
}

Expand Down

0 comments on commit 1ff5e92

Please sign in to comment.