Data layer

Rename the data layer

The default name of the data layer by the global site tag is dataLayer, to use a different name:

  • Update all instances of "dataLayer" in the global site tag snippet to the new name.
  • Add an query parameter named l to the URL to set the new data layer name.
<!-- Global site tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID&l=gDataLayer"></script>
<script>
  window.gDataLayer = window.gDataLayer || [];
  function gtag(){gDataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'GA_MEASUREMENT_ID');
</script>

Custom data layer methods

If you push a function to the data layer, it will be invoked with this set to an abstract data model. This abstract data model can get and set values to a key value store, and also exposes a way to reset the data layer.

Get

The get function on the abstract data model lets you retrieve values that were set.

window.dataLayer.push(function() {
  const existingTime = this.get('time');
  if (existingTime !== null) {
    // Change behavior based on whether or not this value exists...
  } else {
    // ...
  }
})

Set

The set function on the abstract data model lets you set values to retrieve through get.

window.dataLayer.push(function() {
  this.set('time', new Date());
})

Reset

The reset function on the abstract data model lets you reset the data in the data layer. This is most useful in a long-living page where the data layer size continues to grow over time. To reset the data layer, use the following code:

window.dataLayer.push(function() {
  this.reset();
})