Search code examples
javascriptgoogle-tag-managergoogle-analytics-4

How can I extract value from first party cookies via Google Tag Manger Custom Java Scrip Variable


I have the following first party cookie value in an array: {"version":1,"destinations":{},"custom":{"marketingAndAnalytics":true,"advertising":true,"functional":true}}

And I am stuck to get the marketingAndAnalytics value. If it is set to true, I can fire my event tags.

I am using this script:

function() {
  var cookieValue = {{First Party Cookie)}};
  var regex = /marketingAndAnalytics:(\w)/
  var match = cookieValue.match(regex);
  if (match && match['true']) {
    return match['true']
  } else {
    return null
  }
}

Thanks


Solution

  • The script you provided seems to have a few syntax errors and inconsistencies. Here's an updated version that should help you retrieve the value of the "marketingAndAnalytics" property from the cookie:

    function() {
      var cookieValue = '{{First Party Cookie}}';
      var regex = /"marketingAndAnalytics":(\w+)/;
      var match = cookieValue.match(regex);
      if (match && match[1] === 'true') {
        return match[1];
      } else {
        return null;
      }
    }

    Here's a breakdown of the script:

    The {{First Party Cookie}} placeholder should be replaced with the actual code that retrieves the value of the first-party cookie. Make sure to surround it with single quotes to denote it as a string.

    The regular expression pattern /"marketingAndAnalytics":(\w+)/ is used to match the "marketingAndAnalytics" property and capture its value.

    The match variable stores an array of matches. The captured value you're interested in can be accessed with match[1].

    The condition match[1] === 'true' checks if the captured value is equal to 'true'. If it is, the value is returned. Otherwise, null is returned.

    Please note that this script assumes that the provided cookie value is a valid JSON string and follows the specified format. Make sure to adjust the script according to your specific implementation.

    Remember to replace {{First Party Cookie}} with the code that retrieves the actual cookie value in your project.