Reputation: 62
I'm trying to set up a Google tag manager variable to read a URL parameter if it exists, if not, check if the variable exists in the data layer and if not return false.
However, GTM is giving a parse error saying there is a missing ')'. Any help would be much appreciated, not sure if it is my code or if GTM requires specific syntax?
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
function () {
var hid = getParameterByName('hid').length();
if (hid > -1) {
return getParameterByName('hid');
}
else
if (dataLayer[0].emailHash.length >-1) {
return dataLayer[0].emailHash;
}
else
{
return false
}
}
Upvotes: 0
Views: 970
Reputation: 8907
This probably works better if you break it out into two Custom JS variables, as you aren't manipulating global variables:
Variable #1: getParameterByName:
function() {
return function (name){
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
}
Variable #2: testDataLayer:
function () {
var fn_getParameterByName = {{getParameterByName}};
var hid = fn_getParameterByName('hid');
if (hid.length > -1) {
return fn_getParameterByName ('hid');
}
else
if (dataLayer[0].emailHash.length >-1) {
return dataLayer[0].emailHash;
}
else
{
return false
}
}
Upvotes: 1
Reputation: 8637
try with this code (you need to enter script tag):
<script type="text/javascript">
(function (){
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var hid = getParameterByName('hid').length();
if (hid > -1) {
return getParameterByName('hid');
} else if (dataLayer[0].emailHash.length > -1) {
return dataLayer[0].emailHash;
} else {
return false;
}
})();
Upvotes: 0