Skip to content

Commit f170f47

Browse files
dewenGatsbyJS Bot
authored andcommitted
Add dataLayerName check before push in event. (#20551)
* Add dataLayerName check before push in event. * Update browser test after data layer name check change.
1 parent d6a74d6 commit f170f47

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

packages/gatsby-plugin-google-tagmanager/src/__tests__/gatsby-browser.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,4 +69,23 @@ describe(`onRouteUpdate`, () => {
6969

7070
expect(window.dataLayer).toHaveLength(1)
7171
})
72+
73+
it(`registers new data layer variable if dataLayerName is specified`, () => {
74+
const { onRouteUpdate } = getAPI(() => {
75+
process.env.NODE_ENV = `production`
76+
})
77+
const dataLayerName = `fooBarDataLater`
78+
window[dataLayerName] = []
79+
80+
onRouteUpdate(
81+
{},
82+
{
83+
dataLayerName,
84+
}
85+
)
86+
87+
jest.runAllTimers()
88+
89+
expect(window[dataLayerName]).toHaveLength(1)
90+
})
7291
})

packages/gatsby-plugin-google-tagmanager/src/gatsby-browser.js

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,11 @@ exports.onRouteUpdate = (_, pluginOptions) => {
55
) {
66
// wrap inside a timeout to ensure the title has properly been changed
77
setTimeout(() => {
8-
window.dataLayer.push({ event: `gatsby-route-change` })
8+
let data = pluginOptions.dataLayerName
9+
? window[pluginOptions.dataLayerName]
10+
: window.dataLayer
11+
12+
data.push({ event: `gatsby-route-change` })
913
}, 50)
1014
}
1115
}

0 commit comments

Comments
 (0)