# Data layer events

URL: https://docs.ablyft.com/developers/tracking-and-events/datalayer-events/

> Use entries of your data layer to start audiences and to run your own code.



Many websites collect information in a **data layer**: a JavaScript array named `window.dataLayer`. Tag managers such
as Google Tag Manager read it, and your shop or application pushes entries into it, for example when a product is added to
the cart:

```js
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
  event: 'add_to_cart',
  ecommerce: { currency: 'EUR', value: 29.9, coupon: 'SUMMER' }
});
```

An entry usually has an `event` key with its name, plus any other data. ABlyft can react to such entries in two ways:

* in an **audience**, to include visitors only after something has happened (no code needed),
* in **your own code**, with two helper functions.

## Use data layer events in audiences

An audience can start matching only after a certain data layer entry appeared. This is useful to target visitors
who just added something to the cart, who accepted a consent category, or whose entry contains a certain value.

1. Go to **Targeting & Goals → Audiences** and create or edit an audience.

2. Add the targeting block **dataLayer Event**.

3. Fill in the rule:

   | Field          | Description                                                                                                      |
   | -------------- | ---------------------------------------------------------------------------------------------------------------- |
   | **Event name** | The value of the `event` key to look for, for example `add_to_cart`.                                             |
   | **Check**      | What must be true for the entry, see the table below.                                                            |
   | **Property**   | The key to check, for nested data with dots: `ecommerce.coupon`. Not needed for **Event exists**.                |
   | **Value**      | The value to compare with. Not needed for **Event exists**, **property exists** and **property does not exist**. |

4. Save and [attach the audience to your experiment](https://docs.ablyft.com/guides/audiences-and-delivery/audiences/).

### Checks (operators)

| Check                       | The entry matches if …                                                    |
| --------------------------- | ------------------------------------------------------------------------- |
| **Event exists**            | an entry with this event name was pushed. Property and value are ignored. |
| **property exists**         | the property is present in the entry                                      |
| **property does not exist** | the property is missing                                                   |
| **is (exactly)**            | the property equals the value (compared as text)                          |
| **is not (exactly)**        | the property is missing or differs from the value                         |
| **contains**                | the property, as text, contains the value                                 |
| **does not contain**        | the property, as text, does not contain the value                         |
| **is greater than**         | the property, as a number, is larger than the value                       |
| **is less than**            | the property, as a number, is smaller than the value                      |

If the property is an object or a list, ABlyft compares its JSON text.

### How it behaves

* ABlyft looks at entries that are **already in the data layer** (the latest one with this event name counts) and at
  all entries pushed **later**.
* As soon as an entry fulfils the check, the audience counts as matching for the **rest of this page view**. The
  experiments that use the audience are evaluated again right away.
* Nothing is remembered for the next page. After a reload, the data layer must contain a matching entry again.
* Several rules inside one block are combined with OR; several blocks of an audience are combined with AND.

> **The experiment must be on an active page:** An audience trigger only re-evaluates experiments on pages that are already active. Make sure the experiment's
> [page](https://docs.ablyft.com/guides/audiences-and-delivery/pages/) matches the URL where the entry is pushed.

## Choose how ABlyft watches the data layer

The snippet needs to notice new entries. How it does so (**Intercept** or **Polling**) is the project setting **Data layer
watching**, see [Snippet settings](https://docs.ablyft.com/developers/installation/snippet-settings/#data-layer-watching). If another script replaces
`dataLayer.push`, choose **Polling**. The setting applies to the audience rules above and to `watchDataLayerEntry()` below.

## Run code when an entry is pushed

Use these functions in variation, page callback or project code, where `ablyftTools` is available. Both are described in the
[tools reference](https://docs.ablyft.com/developers/reference/javascript-api/tools/#data-layer).

### `watchDataLayerEntry`

Reacts to every entry with the given event name, see [`watchDataLayerEntry`](https://docs.ablyft.com/developers/reference/javascript-api/tools/#watchdatalayerentry).

```js
const stop = ablyftTools.watchDataLayerEntry('add_to_cart', (entry) => {
  console.log('Item added', entry.ecommerce.value);
});

// later, if no longer needed
stop();
```

Example: send a [custom goal](https://docs.ablyft.com/developers/tracking-and-events/custom-goals/) when a lead event occurs. For a purchase
value, see the example in [Revenue tracking](https://docs.ablyft.com/developers/tracking-and-events/revenue-tracking/#take-the-value-from-your-page).

```js
ablyftTools.watchDataLayerEntry('generate_lead', () => {
  window.ablyft.push({ eventType: 'custom', eventName: 'lead' });
});
```

### `checkForDataLayerEntry`

Waits for one specific entry, see [`checkForDataLayerEntry`](https://docs.ablyft.com/developers/reference/javascript-api/tools/#checkfordatalayerentry).
It is useful to start a page with the **Callback** trigger:

```js
ablyftTools.checkForDataLayerEntry(
  [['event', 'page_view'], ['page_location', 'https://www.example.com/test']],
  () => activate()
);
```

See [Dynamic content](https://docs.ablyft.com/developers/application-integration/dynamic-content/#callback-trigger).

## Send experiment information to the data layer

The other direction is also common: your analytics tool should know which variation a visitor saw. For this you can add an
**integration** that runs when a visitor is bucketed or views an experiment. Go to **Integrations → Custom Integrations**,
choose the trigger (**User bucketed** or **Experiment viewed**), and add JavaScript. In the code you can use `project`,
`experiment` and `variation` (each with `id` and `name`), and the variation `metadata`:

```js
dataLayer.push({
  'event': 'experimentViewed',
  'experiment_name': experiment.data.name,
  'variation_name': variation.data.name
});
```

A tag manager can then forward this event to Google Analytics 4. ABlyft's integration documentation describes a
ready-made connection for Google Tag Manager and GA4; contact ABlyft support if you want help to set it up.

## Troubleshooting

* **Audience never matches:** open the browser console and run `window.dataLayer`. Check that the event name is spelled
  exactly like in the audience, and that the property path is correct (case-sensitive).
* **Works on reload but not for events pushed later:** another script may have replaced `dataLayer.push` after ABlyft
  wrapped it. Switch **Data layer watching** to **Polling**.
* **Callback runs twice:** `watchDataLayerEntry` also reports an entry that already existed when you registered. Call
  the stop function, or make your code safe to run twice.
* Turn on [debug mode](https://docs.ablyft.com/developers/debugging/preview-and-live-log/#debug-mode): audience triggers are logged with
  `AUDIENCE TRIGGER activated`.

## Next steps

- [Tools](https://docs.ablyft.com/developers/reference/javascript-api/tools/): All helper functions.
- [Custom goals](https://docs.ablyft.com/developers/tracking-and-events/custom-goals/): Count conversions from your code.
- [Audiences](https://docs.ablyft.com/guides/audiences-and-delivery/audiences/): Combine targeting rules.

