How to fix ReferenceError: datalayer is not defined in Google Tag Manager

I was using Google Tag Manager and custom event tracking to track time on site and was noticing a console error ReferenceError: datalayer is not defined – after investigating I found a good summary on how to use the data layer from Lunametrics.

Here is how I changed the Custom HTML tag to resolve the error.


window.addEventListener("beforeunload", function(e) {
window.dataLayer = window.dataLayer || [];
datalayer.push ({
'event' : 'beforeunload',
'timeOnPage' : new Date().getTime() - {{Page Load Start Time}}
});
});

 

I changed the Custom HTML Tag and this resolved the console error. Notice where I instantiate the dataLayer before pushing the event and timeOnPage.


window.addEventListener("beforeunload", function(e) {
var dataLayer = window.dataLayer = window.dataLayer || [];
dataLayer.push ({
'event' : 'beforeunload',
'timeOnPage' : new Date().getTime() - {{Page Load Start Time}}
});
});