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

feat(gatsby-plugin-google-tagmanager): add option for selfHostedOrigin #32733

Merged
merged 8 commits into from
Aug 30, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions packages/gatsby-plugin-google-tagmanager/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ plugins: [
routeChangeEventName: "YOUR_ROUTE_CHANGE_EVENT_NAME",
// Defaults to false
enableWebVitalsTracking: true,
// Defaults to https://www.googletagmanager.com
selfHostedOrigin: "YOUR_SELF_HOSTED_ORIGIN",
},
},
]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ describe(`pluginOptionsSchema`, () => {
dataLayerName: `YOUR_DATA_LAYER_NAME`,
routeChangeEventName: `YOUR_ROUTE_CHANGE_EVENT_NAME`,
enableWebVitalsTracking: true,
selfHostedOrigin: `YOUR_SELF_HOSTED_ORIGIN`,
})

expect(isValid).toEqual(true)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -180,5 +180,53 @@ describe(`gatsby-plugin-google-tagmanager`, () => {
expect(mocks.setHeadComponents.mock.calls[0].length).toBe(1)
expect(headConfig.key).toBe(`plugin-google-tagmanager`)
})

it(`should set selfHostedOrigin as googletagmanager.com by default`, () => {
const mocks = {
setHeadComponents: jest.fn(),
setPreBodyComponents: jest.fn(),
}
const pluginOptions = {
id: `123`,
includeInDevelopment: true,
}

onRenderBody(mocks, pluginOptions)
const [headConfig] = mocks.setHeadComponents.mock.calls[0][0]
const [preBodyConfig] = mocks.setPreBodyComponents.mock.calls[0][0]

// eslint-disable-next-line no-useless-escape
expect(headConfig.props.dangerouslySetInnerHTML.__html).toContain(
`https://www.googletagmanager.com/gtm.js`
)
expect(preBodyConfig.props.dangerouslySetInnerHTML.__html).toContain(
`https://www.googletagmanager.com/ns.html`
)
})

it(`should set selfHostedOrigin`, () => {
const selfHostedOrigin = `YOUR_SELF_HOSTED_ORIGIN`
const mocks = {
setHeadComponents: jest.fn(),
setPreBodyComponents: jest.fn(),
}
const pluginOptions = {
id: `123`,
includeInDevelopment: true,
selfHostedOrigin: selfHostedOrigin,
}

onRenderBody(mocks, pluginOptions)
const [headConfig] = mocks.setHeadComponents.mock.calls[0][0]
const [preBodyConfig] = mocks.setPreBodyComponents.mock.calls[0][0]

// eslint-disable-next-line no-useless-escape
expect(headConfig.props.dangerouslySetInnerHTML.__html).toContain(
`${selfHostedOrigin}/gtm.js`
)
expect(preBodyConfig.props.dangerouslySetInnerHTML.__html).toContain(
`${selfHostedOrigin}/ns.html`
)
})
})
})
3 changes: 3 additions & 0 deletions packages/gatsby-plugin-google-tagmanager/src/gatsby-node.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,7 @@ exports.pluginOptionsSchema = ({ Joi }) =>
`Name of the event that is triggered on every Gatsby route change.`
),
enableWebVitalsTracking: Joi.boolean().default(false),
selfHostedOrigin: Joi.string()
.default(`https://www.googletagmanager.com`)
.description(`The origin where GTM is hosted.`),
})
29 changes: 23 additions & 6 deletions packages/gatsby-plugin-google-tagmanager/src/gatsby-ssr.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,20 @@
import React from "react"
import { oneLine, stripIndent } from "common-tags"

const generateGTM = ({ id, environmentParamStr, dataLayerName }) => stripIndent`
const generateGTM = ({
id,
environmentParamStr,
dataLayerName,
selfHostedOrigin,
}) => stripIndent`
(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+'${environmentParamStr}';f.parentNode.insertBefore(j,f);
'${selfHostedOrigin}/gtm.js?id='+i+dl+'${environmentParamStr}';f.parentNode.insertBefore(j,f);
})(window,document,'script','${dataLayerName}', '${id}');`

const generateGTMIframe = ({ id, environmentParamStr }) =>
oneLine`<iframe src="https://www.googletagmanager.com/ns.html?id=${id}${environmentParamStr}" height="0" width="0" style="display: none; visibility: hidden" aria-hidden="true"></iframe>`
const generateGTMIframe = ({ id, environmentParamStr, selfHostedOrigin }) =>
oneLine`<iframe src="${selfHostedOrigin}/ns.html?id=${id}${environmentParamStr}" height="0" width="0" style="display: none; visibility: hidden" aria-hidden="true"></iframe>`

const generateDefaultDataLayer = (dataLayer, reporter, dataLayerName) => {
let result = `window.${dataLayerName} = window.${dataLayerName} || [];`
Expand Down Expand Up @@ -41,6 +46,7 @@ exports.onRenderBody = (
defaultDataLayer,
dataLayerName = `dataLayer`,
enableWebVitalsTracking = false,
selfHostedOrigin = `https://www.googletagmanager.com`,
}
) => {
if (process.env.NODE_ENV === `production` || includeInDevelopment) {
Expand All @@ -60,6 +66,8 @@ exports.onRenderBody = (
)
}

selfHostedOrigin = selfHostedOrigin.replace(/\/$/, ``)

const inlineScripts = []
if (enableWebVitalsTracking) {
// web-vitals/polyfill (necessary for non chromium browsers)
Expand All @@ -83,7 +91,12 @@ exports.onRenderBody = (
dangerouslySetInnerHTML={{
__html: oneLine`
${defaultDataLayerCode}
${generateGTM({ id, environmentParamStr, dataLayerName })}`,
${generateGTM({
id,
environmentParamStr,
dataLayerName,
selfHostedOrigin,
})}`,
}}
/>
)
Expand All @@ -94,7 +107,11 @@ exports.onRenderBody = (
<noscript
key="plugin-google-tagmanager"
dangerouslySetInnerHTML={{
__html: generateGTMIframe({ id, environmentParamStr }),
__html: generateGTMIframe({
id,
environmentParamStr,
selfHostedOrigin,
}),
}}
/>,
])
Expand Down