# JavaScript API

URL: https://docs.ablyft.com/developers/reference/javascript-api/

> The global ablyft object, its methods, events and flags.



The snippet exposes a single global object, `window.ablyft`.

## Overview

| Member                        | Purpose                                                 | Details                                              |
| ----------------------------- | ------------------------------------------------------- | ---------------------------------------------------- |
| `ablyft.push(event)`          | Send events and commands (goals, pages, consent, …)     | [push](https://docs.ablyft.com/developers/reference/javascript-api/push/)   |
| `ablyft.get(type, argument?)` | Read state and project data                             | [get](https://docs.ablyft.com/developers/reference/javascript-api/get/)     |
| `ablyft.getTools()`           | Utility helpers (cookies, URLs, polling, data layer, …) | [tools](https://docs.ablyft.com/developers/reference/javascript-api/tools/) |
| `ablyft.reInit(options?)`     | Re-run ABlyft, e.g. after SPA navigation                | [below](#ablyftreinit)                               |

## Use the API before the snippet has loaded

Create `window.ablyft` as an array and push commands into it. When the snippet loads, it replaces the
array with the real API and replays your queued commands:

* `forceVariation` commands are applied immediately.
* All other commands are replayed once the project has been initialized.

```js
window.ablyft = window.ablyft || [];

window.ablyft.push({
  eventType: 'custom',
  eventName: 'newsletter-signup',
});
```

Only `push()` can be queued this way. `get()`, `getTools()` and `reInit()` exist only after the snippet has loaded.
To know when that is the case, listen for the [`ablyftApiReady` event](#events).

## ablyft.reInit()

Re-runs ABlyft on the current page. Use it after your application changed the page without a full reload.
See also [SPA navigation](https://docs.ablyft.com/developers/application-integration/spa-navigation/).

```js
ablyft.reInit(); // re-evaluate pages and experiments

ablyft.reInit({ resetStates: true }); // additionally forget active pages and experiments first
```

| Option        | Type    | Default | Description                                                                                                                                                                               |
| ------------- | ------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `resetStates` | boolean | `false` | Clears the list of active pages and experiments and resets internal signals before running again. Use it when the whole view is replaced, for example after a login or a language switch. |

Without options, pages that are already active and still match are left alone. New matching pages are activated; pages
that do not match anymore are handled according to their deactivation mode.

In projects configured as single-page application, all experiments the visitor is bucketed in are initialized again,
so that resets and goals are applied.

## ablyft.getTools()

Returns the tools object. Identical to `ablyft.get('tools')`. See [Tools](https://docs.ablyft.com/developers/reference/javascript-api/tools/).

```js
const tools = ablyft.getTools();
console.log(tools.getUrlParameter('utm_source'));
```

## Events

The snippet dispatches the following events on `document`.

| Event                | When                                                  | Payload                     |
| -------------------- | ----------------------------------------------------- | --------------------------- |
| `ablyftApiReady`     | `window.ablyft` is available (before initialization)  | –                           |
| `ablyft_initialized` | Project initialized (fired again on every `reInit()`) | –                           |
| `ablyftError`        | The snippet logs an error                             | `event.detail.msg` (string) |

```js
document.addEventListener('ablyftApiReady', () => {
  console.log('ABlyft API is ready', ablyft.get('data'));
});

document.addEventListener('ablyft_initialized', () => {
  console.log('Active pages:', ablyft.get('activePageIds'));
});

document.addEventListener('ablyftError', (event) => {
  console.warn('ABlyft error:', event.detail.msg);
});
```

> `ablyftError` is only dispatched while snippet logging is enabled (debug mode of the project).
> Make sure the event listener is registered before the snippet runs if you need early errors.

## Window flags

Optional flags you can set before the snippet loads.

| Flag                              | Effect                                                                                             |
| --------------------------------- | -------------------------------------------------------------------------------------------------- |
| `window.ablyftAllowIframe = true` | Allow the snippet to run inside an iframe (it exits otherwise, unless the project allows iframes). |

```html
<script>
  window.ablyftAllowIframe = true;
</script>
<script src="https://cdn.ablyft.com/s/{projectId}.js"></script>
```

> The snippet only starts once per page. If another ABlyft snippet is already running, a second one logs a warning and exits.

