简体   繁体   中英

Google Tag Manager Custom JavaScript

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
}
}

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
    }
}

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;
    }    
})();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM