Sameer
Sameer

Reputation: 71

Google Tag Manager custom JavaScript errror

I have return below JavaScript function to read cookie name and value. I am able to fetch name and value when I use the script in Chrome and Firefox browser console.

                  getCookie('xyz') ; 

              function getCookie(name)
               {
            var re = new RegExp(name + "=([^;]+)");
            var value = re.exec(document.cookie);
         return (value != null) ? unescape(value[1]) : null;
            }

but when I use same code in Google Tag Manager by using Custom JavaScript variable I am getting error "parenthesis ( required".

I am not able to figure out what is error as this code is running everywhere except in Google Tag Manager.

Upvotes: 0

Views: 1060

Answers (2)

Josh berry-jenkins
Josh berry-jenkins

Reputation: 11

I usually deal with cookie sets & gets via a custom HTML tag as I believe the custom Javascript requires a return value. So something along the lines of this:

<script>
(function() {

function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

console.log(getCookie("xyz"));
</script>

})();

The above would output a log to the console with the value of a cookie named xyz whenever the tag's trigger is fired.

If you wanted to store and use this cookie value within GTM you would then need to pass this variable on and store it, either using the cookie variable or via the dataLayer.

Upvotes: 0

Eike Pierstorff
Eike Pierstorff

Reputation: 32760

The solution is to use the built-in "Cookie" Variable (go to variables, new, 1st Party Cookie, enter a name for the variable and in the config the name of the cookie). No need for homegrown solutions.

To strictly answer the question, custom javascript variables must be written as an anonymous function with a return value:

function() {
return "something";
}

I'm sure there is a workaround to pass parameters (i.e. the cookie name) but that's not typically how custom javascript variables are used and you do not need this for your use case.

if you insist on your function you could always return it via a custom javascript variable:

function() {
return function (name) {
            var re = new RegExp(name + "=([^;]+)");
            var value = re.exec(document.cookie);
         return (value != null) ? unescape(value[1]) : null;
            }
}

Store it in a custom javascript variable called getCookie and access in in custom HTML tags via {{getCookie}}('xyz'). Not a very good idea but possible.

Upvotes: 1

Related Questions