> ## Documentation Index
> Fetch the complete documentation index at: https://docs.metricanic.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Tracking script functions

> Call the tracking script from your page code to connect buttons, pass the click ID and send events.

The tracking script adds the global function `metricanicCallback` to the page. Use it in your own scripts to connect buttons, read visit data and send events.

The page needs the installed tracking snippet. See [Install the tracking script](/tracking/landings#install-the-tracking-script). On **Hosted** landings, publish with **Add Direct Tracking** enabled.

## Call a function

Put your code inside `metricanicCallback`:

```js theme={null}
metricanicCallback((api) => {
	console.log(api.getClickId());
});
```

The code runs after the visit is registered and the page's offer links are connected. If tracking is already ready, it runs immediately. If tracking fails, it does not run. Place your code after the tracking snippet.

## Functions

| Function                 | Returns                                                      | Use it to                                          |
| ------------------------ | ------------------------------------------------------------ | -------------------------------------------------- |
| `getClickId()`           | Click ID of the visit                                        | Pass the visit to a form, CRM or order system      |
| `getTokens()`            | Traffic source tokens, such as `{ t1: 'banner-a' }`          | Read source values. Token 1 is `t1`                |
| `getPage()`              | `type`, `url`, `landingId` and `offerId` of the visit        | Show content for the selected offer                |
| `getOfferLink()`         | Offer URL selected for the visit                             | Open the offer from your own button                |
| `getClickLink()`         | Tracker link that records a click and redirects to the offer | Link a widget or element where you cannot add code |
| `generateLinks(options)` | Connected elements                                           | Connect buttons added after the page loaded        |
| `registerClick()`        | Promise                                                      | Record a click from your own button                |
| `logEvent(options)`      | Promise                                                      | Send an event, such as a quiz step or form submit  |

## Connect buttons added later

When the page loads, the script connects links to `https://<tracking domain>/click` and elements with `data-dtp-link`, including buttons. After a popup, quiz or page builder adds buttons, call:

```js theme={null}
metricanicCallback((api) => {
	api.generateLinks();
});
```

Call it again after each change. An element is never connected twice.

| Option     | Default                    | Description                                                                                                      |
| ---------- | -------------------------- | ---------------------------------------------------------------------------------------------------------------- |
| `selector` | `[data-dtp-link]`          | CSS selector of the elements to connect                                                                          |
| `target`   | The element's own `target` | `_blank` opens the offer in a new tab. `replace` opens it in place of the landing, so **Back** skips the landing |
| `register` | `true`                     | `false` connects the element without recording clicks                                                            |

## Build your own offer button

Use this when a button needs its own logic, such as form validation, before opening the offer:

```js theme={null}
metricanicCallback((api) => {
	document.querySelector('#continue').addEventListener('click', () => {
		api.registerClick().catch(console.error);
		window.location.href = api.getOfferLink();
	});
});
```

Call `registerClick()` once per click. Do not use it on links the script already connects. They record clicks automatically.

## Pass the click ID to a form

Save the click ID with the lead so your CRM can send events for this visit later:

```html theme={null}
<input type="hidden" name="clickid" id="clickid" />
<script>
	metricanicCallback((api) => {
		document.querySelector('#clickid').value = api.getClickId();
	});
</script>
```

Your CRM sends the event to the [incoming event URL](/conversions/incoming-events) with this click ID.

## Send an event

```js theme={null}
metricanicCallback((api) => {
	api.logEvent({ idx: 3, txuid: 'quiz-done' });
});
```

| Field    | Description                                                                            |
| -------- | -------------------------------------------------------------------------------------- |
| `idx`    | Event slot from `1` to `10`. Default `1`                                               |
| `txuid`  | Event identifier. Repeated calls with the same value count once per visit and slot     |
| `payout` | Revenue, such as `24.50`, for an event with **Revenue** set to **From incoming event** |
| `value`  | Number added to **Value N** of the event                                               |

* Configure the slot in the campaign's **Events and rules**. See [Decide what counts as a conversion](/conversions/goals).
* Without `txuid`, every call adds a new event. Use a fixed `txuid` for steps that must count once, such as `'form-open'`.
* Visitors can see and change browser requests. Send revenue from your server or affiliate network instead.
* `logEvent()` completes when the request is sent, not when the event is recorded. Check the result in **Events**.

## Handle a failed start

```js theme={null}
metricanicCallback.onError((error) => {
	console.error(error.code, error.message);
});
```

The handler runs once if the script cannot load (`script_load_failed`) or the visit cannot be registered (`invalid_response`, `visit_failed`). Callbacks then do not run, and offer links keep their original addresses.
