# JS events

AB Tasty's tag dispatches JavaScript events to the `window` or  `document` to share information with other scripts. These events can be used by anyone who wants to monitor tag activity.

### Dispatching events

#### Tag reloading

{% hint style="warning" %}
**Not available in** `window.ABTasty.eventState`
{% endhint %}

If the "Automatic reload of the framework" is activated in [your account settings](https://app2.abtasty.com/settings/framework), the tag dispatches the following at each start and reload:

**Event details:**

* **Event name:** `resetActionTracking`&#x20;
* **Event prefix:** `abtasty`&#x20;
* **Purpose:** Removes all previous action tracking listeners used by the tag
* **Target element:** `document`

**Listen for the event:**

```javascript
document.addEventListener('abtasty_resetActionTracking', () => {
  // do something...
});
```

#### Consent validation

**Event details:**

* **Event name:** `consentValid`&#x20;
* **Event prefix:** `abtasty`&#x20;
* **Target element:** `window`

**Listen for the event:**

```javascript
window.addEventListener('abtasty_consentValid', (event) => {
  console.log(event.detail);
  // do something...
});
```

**Type `event.detail`:**

| Key        | Type   | Description                                                                                                                                                    |
| ---------- | ------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| mode       | string | The mode used by the tag to determine if the visitor gave his consent. It should be equal to `window.ABTasty.accountData.accountSettings.waitForConsent.mode`. |
| consentFor | array  | List of rights accorded to our tag during the consent validation.                                                                                              |

**Mode possible values:**

* `any_cookie`: Tag waits until any cookie is added to website.
* `custom_js`: Tag waits until the user's JavaScript code returns true or resolves.&#x20;
* `didomi`: Tag waits until the Didomi SDK registers visitor consent.
* `specific_cookie`: Tag waits until the specified cookie with corresponding value is added.
* `user_action`: Tag waits until the user performs an action (scroll, click, etc.).

**ConsentFor possible value:**

* `start`: Tag has the rights to start running.
* `test`: Tag can run A/B tests, multipages tests and multivariate tests.
* `perso`: Tag can run personalizations campaigns.
* `aa`: Tag can run A/A Tests.
* `patch`: Tag can run patch campaigns.
* `redirection`: Tag can run redirection campaigns.
* `storage`: Tag can store data in cookies, localStorage, or sessionStorage.
* `collect`: Tag can send collected data to AB tasty's collection endpoint `ariane.abtasty.com`.
* `dmp`: Tag can access DMP information based on visitor Id.
* `geoloc`: Tag can fetch complete visitor geolocation data.

#### Executed Campaign

Every time a campaign is successfully executed, an event is triggered with the campaign information.

**Event details:**

* **Event name:** `executedCampaign`&#x20;
* **Event prefix:** `abtasty`&#x20;
* **Target element:** `window`

**Listen for the event:**

```javascript
window.addEventListener('abtasty_executedCampaign', (event) => {
  console.log(event.detail);
  // do something...
});
```

**Type `event.detail`:**

| Key         | Type    | Description                                                                           |
| ----------- | ------- | ------------------------------------------------------------------------------------- |
| campaignId  | integer | The ID of the executed campaign.                                                      |
| variationId | integer | The ID of the executed variation.                                                     |
| status      | string  | The status of the campaign. Possible values: `accepted` or `accepted_by_redirection`. |
| type        | string  | The type of the campaign. Possible values: `ab`, `mpt`, `mvt`, `sp`, `mpp` or `mep`.  |

**Type details:**

* `ab`: Campaign is an A/B Test
* `mpt`: Campaign is a Multipage test child
* `mvt`: Campaign is a Multivariate test child
* `sp`: Campaign is a Simple personalization child
* `mpp`: Campaign is a Multipage personalization child
* `mep`: Campaign is a Multiexperience personalization child
* `subsegment`: Campaign is a personalization child

#### Tag executed

When the tag completes the execution of all features at least once, an event is dispatched. If the tag uses intervals, the event is dispatched after the first interval iteration. For criteria that are verified multiple times, the event is dispatched once each criterion has been verified at least once.

**Event details:**

* **Event name:** `tagContentExecuted`&#x20;
* **Event prefix:** `abtasty`&#x20;
* **Purpose:** The main goal of the event is to say that the tag has been fully executed (at least once).&#x20;
* **Target element:** `window`

**Listen for the event:**

```javascript
window.addEventListener('abtasty_tagContentExecuted', () => {
  // do something...
});
```

#### Tracking initialized

Once the tag has defined the tracking method in the `window`, it dispatches this event to notify that these methods are ready to use. The global methods are:

* [window.abtasty.send()](https://docs.abtasty.com/client-side/tag-methods-variables#tracking-methods)
* [window.ABTastyClickTracking()](https://docs.abtasty.com/client-side/tag-methods-variables#tracking-methods)
* [window.ABTastyEvent()](https://docs.abtasty.com/client-side/tag-methods-variables#tracking-methods) *(deprecated)*
* [window.\_abtasty.push()](https://docs.abtasty.com/client-side/tag-methods-variables#tracking-methods) *(deprecated)*

**Event details:**

* **Event name:** `trackingInitialized`&#x20;
* **Event prefix:** `abtasty`&#x20;
* **Purpose:** This event notifies you when tracking methods are available, allowing you to send transaction hits or other tracking data.
* **Target element:** `window`

**Listen for the event:**

```javascript
window.addEventListener('abtasty_trackingInitialized', () => {
  // do something with window.abtasty.send() ...
});
```

### Event state

For every JavaScript event dispatched by the tag, you can find a status in `window.ABTasty.eventState`.

#### `eventState`

> Type: Object

All the information about the dispatched or soon-to-be dispatched events.

```javascript
window.ABTasty.eventState
```

An object with the `name` of the event *(without the prefix)* as key and `eventState` as value.

**Type: `eventState`**

| Key           | Type   | Description                                                                                                               |
| ------------- | ------ | ------------------------------------------------------------------------------------------------------------------------- |
| **status**    | string | Status of the event. `loading` means that event has not been dispatched. `complete` means that event has been dispatched. |
| **detail**    | array  | The details linked to the event. Could contain multiple objects as some events are dispatched multiple times.             |
| **detail\[]** | object | The details of one event.                                                                                                 |

### Example of code to listen event

#### Wait to send transaction

```javascript
const removeListeners = () => {
  window.removeEventListener('abtasty_trackingInitialized', sendTransaction);
  document.removeEventListener('abtasty_resetActionTracking', removeListeners);
};

const sendTransaction = () => {
  window.abtasty.send('transaction', {
    tid: 'OD564', //Transaction ID
    ta: 'Purchase', //Transaction Affiliation - Name of the transaction goal
    tr: 15.47, //Transaction Revenue
    icn: 12, //Number of items
    // You can add all the data related to your transaction...
  });

  // Remove listener for SPA websites
  removeListeners();
};

if (
  typeof window.ABTasty !== 'undefined' &&
  typeof window.ABTasty.eventState !== 'undefined' &&
  !!window.ABTasty.eventState['trackingInitialized'] &&
  window.ABTasty.eventState['trackingInitialized'].status === 'complete'
  // You might also check if the user is on the purchase confirmation page
) {
  sendTransaction();
} else {
  window.addEventListener('abtasty_trackingInitialized', sendTransaction);

  // Remove listener for SPA websites
  document.addEventListener('abtasty_resetActionTracking', removeListeners);
}
```

#### Wait for specific campaign execution

```javascript
const specificCampaignId = 123456;

const campaignExecuted = (detail) => {
  const campaignId = detail.campaignId;
  const campaignVariation = detail.variationId;
  console.log(`Campaign ${campaignId} has been executed with variation ${variationId}`);
}

if (
  typeof window.ABTasty !== 'undefined' &&
  typeof window.ABTasty.eventState !== 'undefined' &&
  !!window.ABTasty.eventState['executedCampaign'] &&
  window.ABTasty.eventState['executedCampaign'].status === 'complete'
) {
  window.ABTasty.eventState['executedCampaign'].detail.forEach((campaignDetail) => {
    if (campaignDetail.campaignId === specificCampaignId) campaignExecuted(campaignDetail);
  });
} else {
  window.addEventListener('abtasty_executedCampaign', (e) => {
    if (e.detail.campaignId === specificCampaignId) campaignExecuted(e.detail);
  });
}
```

### Actionning events

Those events are another type of event that help you interacting with the Tag and request a specific action.

#### Targeting check or recheck

This CustomEvent allows you to start *(or restart if already triggered by the Tag)* the evaluation of the targeting conditions, either fully or partially, for a specified campaign.

**Event details:**

* **Event name:** `checkTargeting`&#x20;
* **Event prefix:** `abtasty`&#x20;
* **Purpose:** Allowing external/custom scripts to start or restart the targeting check.&#x20;
* **Listen element:** `window`

**Actionning the event:**

```javascript
const detail = { campaignId: 123456, withUrl: false, shouldCheckAll: false };
const event = new CustomEvent('abtasty_checkTargeting', { detail: detail });
window.dispatchEvent(event);
```

**Type `event.detail`:**

| Key            | Type    | Description                                                                                                                |
| -------------- | ------- | -------------------------------------------------------------------------------------------------------------------------- |
| campaignId     | integer | The campaign ID whose targeting conditions will be checked.                                                                |
| withUrl        | boolean | Determines whether the tag should check URL targeting conditions.                                                          |
| shouldCheckAll | boolean | Determines whether the tag should check all targeting conditions or only those that may have changed since the last check. |

*\* We split criteria that shouldn't change during the execution (URL, user-agent, geolocation, screen size...) from the one that may change (element, datalayer, events...).*

The event can only be applied if the specified campaign has one of the following [status](https://docs.abtasty.com/client-side/tag-campaign-types#campaign-status):

* `currently_checking`
* `pending`
* `target_by_event_pending`
* `qa_parameters_rejected`
* `target_pages_rejected`
* `trigger_rejected`
* `segment_rejected`

{% hint style="warning" %}
You don't need to use this event after a URL change, as the tag automatically reloads its targeting when the "automatic reload of the framework" ([See settings](https://app2.abtasty.com/settings/framework)) is enabled (enabled by default).
{% endhint %}

#### DataLayer last entry event

{% hint style="danger" %}
This event is deprecated.
{% endhint %}

**Event name:** `DLLastEntry`\
**Event prefix:** `abtasty`\
**Main goal:** Activate data layer trigger to check last entry of data layer array.\
**Listen element:** `window`

This event is meant to be used when the standard trigger builder options (`loading`, `periodical` and `custom event`) are not possible to use. In some situations, DataLayer entries are added under specific conditions and it is not possible to catch and verify the last one that has been added (for example: DataLayer stacking up on each page with a single-page app).

To catch the last added entry, the `abtasty_DLLastEntry` event needs to be dispatched after the code responsible for updating the DataLayer.

{% hint style="warning" %}
Make sure you fire the event after the tag has been executed ([see topic above](#tag-executed)).&#x20;
{% endhint %}

```javascript
// the event should be dispatched immediately after DL has been updated
window.dispatchEvent(new Event('abtasty_DLLastEntry'));
```

#### Granting consent

This CustomEvent allows you to tell the tag that the visitor has granted consent for being tracked and exposed to campaigns by/from AB Tasty *(depending on your* [*account settings*](https://app2.abtasty.com/settings/cookies/deposit)*)*.

**Event name:** `grantConsent`\
**Event prefix:** `abtasty`\
**Main goal:** Granting consent to the tag.\
**Listen element:** `window`

**Actionning the event:**

```javascript
const event = new CustomEvent('abtasty_grantConsent', {});
window.dispatchEvent(event);
```

**Additional consent variable**

Additionaly to these CustomEvents, you can also set the variable `window.abtastyGrantConsent` to `true` to grant consent at the initialization of the tag.

For example, if you are not sure if the AB Tasty tag is executed before or after the script granting consent, you could do:

```javascript
const grantAbtConsent = () => {
  const event = new CustomEvent('abtasty_grantConsent', {});
  window.dispatchEvent(event);
};

// Check if tag has been executed
if (
  typeof window.ABTasty !== 'undefined' &&
  typeof window.ABTasty.eventState !== 'undefined' &&
  !!window.ABTasty.eventState['tagContentExecuted'] &&
  window.ABTasty.eventState['tagContentExecuted'].status === 'complete'
) {
  grantAbtConsent();
} else {
  // Wait for tag execution
  window.addEventListener('abtasty_tagContentExecuted', grantAbtConsent);
}
```

Or using a variable:

```javascript
const event = new CustomEvent('abtasty_grantConsent', {});
window.dispatchEvent(event);
window.abtastyGrantConsent = true;
```

{% hint style="warning" %}
The tag checks the variable value only once with no continuous monitoring. Setting the value to `false` after tag execution is not going to revoke the consent.
{% endhint %}

#### Revoking consent

This CustomEvent allows you to tell the tag that the visitor has revoked his consent and doesn't want to be tracked anymore by AB Tasty *(depending on your* [*account settings*](https://app2.abtasty.com/settings/cookies/deposit)*)*.

**Event name:** `revokeConsent`\
**Event prefix:** `abtasty`\
**Main goal:** Revoking consent of the tag.\
**Listen element:** `window`

**Actionning the event:**

```javascript
const event = new CustomEvent('abtasty_revokeConsent', {});
window.dispatchEvent(event);
```

#### Bring Your Own ID check

This CustomEvent allows you to ask the tag to recheck if BYOID condition is correct. And if yes, continue to be executed.

**Event name:** `checkByoid`\
**Event prefix:** `abtasty`\
**Main goal:** Get the custom visitor ID and use it according to [BYOID configuration](https://app2.abtasty.com/settings/tracking/visitor-id-management).\
**Listen element:** `window`

**Actionning the event:**

```javascript
const event = new CustomEvent('abtasty_checkByoid', {});
window.dispatchEvent(event);
```
