I want to implement the Enhanced Ecommerce with Google Tag Manager and I want to push some data for the tag Universal Analytics.
I have always created the dataLayer before the GTM script, but now I need to send more data with dataLayer.push
And it doesn't work, datalaLayer.push
only works if it happens just before the GTM script starts.
Example. This works:
<script>
<head>
dataLayer = [{
'google_tag_params': {
'ecomm_pagetype': 'category',
'ecomm_category': '{{ $resource->seo->h1 }}',
}
}];
dataLayer.push({
'ecommerce': {
'currencyCode': 'EUR',
'impressions': [
{
'id': '12312',
'price': 24,
'category': 'wfwefwerwerwer',
'position': 2,
'name': 'wfwefwerwerwer',
'brand': 'My Brand',
'list': 'Product List',
}
]
}
});
(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','GTM-XXXXXX');
</script>
</head>
But if I use dataLayer.push after the GTM script does not work, no data is sent and no errors are reported.
This isn't working for me:
<head>
<script>
dataLayer = [{
'google_tag_params': {
'ecomm_pagetype': 'category',
'ecomm_category': '{{ $resource->seo->h1 }}',
}
}];
(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','GTM-XXXXXX');
</script>
</head>
<body>
//something content html here
<footer></footer>
<script>
dataLayer.push({
'ecommerce': {
'currencyCode': 'EUR',
'impressions': [
{
'id': '12312',
'price': 24,
'category': 'wfwefwerwerwer',
'position': 2,
'name': 'wfwefwerwerwer',
'brand': 'My Brand',
'list': 'Product List',
}
]
}
});
</script>
</body>
window.dataLayer.push
is actually PATCHED by GTM to run its own code. It isn't just a dumb array sitting on the page anymore. So that's how you're able to add to it later. Typewindow.dataLayer.push
in the browser console and you'll see it's a custom function in gtm.js – Holierthanthouvar
part of declaring dataLayer. You can use var, or just add it to the window namespacewindow.dataLayer
– Jackquelin