Sometimes we may be in the situation that we need to know if some info had been already pushed into Google Tag Manager’s dataLayer in order to take some action. For example we may need to know if some custom event it’s already in the dataLayer in order to prevent something to be fired twice, or we may need to check if some value is already in place.
The following snippet, will help us to know that info, looping thru all the dataLayer pushes and returning -1 if the key-value was not found, or the current dataLayer push index that matches.
var isValueInDatalayer = function($key, $val) {
var res = -1;
var dlname;
for (i in window.google_tag_manager) {
if(typeof(window.google_tag_manager[i])=="object" && window.google_tag_manager[i].gtmDom)
dlname = i;
}
if (typeof (window.google_tag_manager) != "undefined") {
for (i in window[dlname]) {
if (!$val & $val!='') {
if (window[dlname][i][$key]) {
return i;
}
} else {
if (window[dlname][i][$key] && window[dlname][i][$key] == $val) {
return i;
}
}
}
}
return res;
};
Let’s see how why can use it, we’re going to imagine that we are on a vanilla GTM container and with no dataLayer pushes from the page:
isValueInDatalayer('event');
This call above will return 0, since it will match the first event key pushed.
isValueInDatalayer('event','gtm.load');
The call above will return 2, and the gtm.load event was found on the 2 position within the dataLayer pushes array (take note that it starts with on 0).
isValueInDatalayer('non-existent-key');
isValueInDatalayer('event','non-existent-event-value');
The two last example will return -1, since they won’t match the current data in our dataLayer.
If you’re using a custom dataLayer variable name, there’s no need for you to modify the code since it’ll autodiscover your current dataLayer variable name.
Let me know any improvement or ideas for this useful function on the comments 🙂
Leave a Reply