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

# JS SDK: Subscribe to Referral and Cookie Ready Events

> Use the Kiflo JS event system to react in real time when the SDK loads or a referral tracking cookie becomes available on the page.

The Kiflo JS SDK can emit events that notify your code when the snippet has finished loading or when a referral tracking cookie is available. Subscribing to these events lets you run custom logic at exactly the right moment — the most common use case is injecting a partner tracking code into a hidden field in your sign-up or contact form so it gets submitted along with the user's data.

## Enable events in your snippet

The standard Kiflo snippet does not include event support by default. To enable it, replace your existing snippet with the extended version below, which adds a `callbacks` array and an `on` function:

```javascript theme={null}
var kjs = window.kjs || function (a) {
  var c = {
    apiKey: a.apiKey,
    callbacks: [],
    on: function(e, b) { c.callbacks.push([e, b]) }
  };
  var d = document;
  setTimeout(function () {
    var b = d.createElement("script");
    b.src = a.url || "https://cdn.kiflo.com/k.js", d.getElementsByTagName("script")[0].parentNode.appendChild(b)
  });
  return c;
}({ apiKey: "YOUR_API_KEY" });
```

The two key additions are **line 4** (`callbacks: []`) and **line 5** (`on: function(...)`). Everything else stays the same. Replace `YOUR_API_KEY` with your actual API key from Kiflo's Integration settings.

<Note>
  Place this extended snippet in the `<head>` of your page, just as you would the standard snippet. The `kjs` variable is what you call `.on(...)` on to register event listeners.
</Note>

## Subscribing to events

Once the extended snippet is in place, call `kjs.on(eventName, callback)` to subscribe. You can subscribe to as many events as you need, and register multiple listeners for the same event.

```javascript theme={null}
kjs.on('ready', function(trackingCode) {
  // fires every time the Kiflo snippet loads
});

kjs.on('cookie.ready', function(trackingCode) {
  // fires only when a referral tracking cookie is present
});
```

***

## Event: `ready`

The `ready` event fires every time the Kiflo JS snippet finishes loading on the page. It is **always** raised — whether or not the visitor arrived through a partner referral link. Use this event when you need to run code that depends on the SDK being available, regardless of whether a tracking cookie exists.

**Parameters:**

<ParamField body="trackingCode" type="string | undefined">
  The referral tracking code stored in the browser cookie, or `undefined` if no tracking cookie is present for the current visitor.
</ParamField>

**Example:**

```javascript theme={null}
kjs.on('ready', function(trackingCode) {
  console.log(
    'Kiflo is ready. Tracking code (may be empty):',
    trackingCode
  );

  // Inject the tracking code into a hidden form field
  var hiddenField = document.getElementById('kifloTrackingCode');
  if (hiddenField) {
    hiddenField.value = trackingCode || '';
  }
});
```

<Tip>
  Use the `ready` event to populate hidden form fields unconditionally. If `trackingCode` is `undefined`, the hidden field receives an empty string, and you can filter those out on the server side. This avoids race conditions where the form is submitted before the SDK loads.
</Tip>

***

## Event: `cookie.ready`

The `cookie.ready` event fires only when a referral tracking cookie is available — either because it was already set on a previous visit, or because it was just written for the first time as the current page loaded. It will **not** fire if the visitor has no partner referral cookie.

**Parameters:**

<ParamField body="trackingCode" type="string">
  The referral tracking code from the browser cookie. This value is always a non-empty string when `cookie.ready` fires.
</ParamField>

**Example:**

```javascript theme={null}
kjs.on('cookie.ready', function(trackingCode) {
  console.log('Referral tracking code is available:', trackingCode);

  // Inject into a hidden form field
  var hiddenField = document.getElementById('kifloTrackingCode');
  if (hiddenField) {
    hiddenField.value = trackingCode;
  }
});
```

<Note>
  Because `cookie.ready` only fires for visitors with an active referral cookie, it will not run for organic visitors who arrived directly. If you need to handle both cases, use `ready` instead.
</Note>

***

## Choosing the right event

| Requirement                                                                   | Use            |
| ----------------------------------------------------------------------------- | -------------- |
| Populate a hidden field for all visitors (leave blank if no referral)         | `ready`        |
| Run logic only when a referral partner is identified                          | `cookie.ready` |
| Know exactly when the SDK is available before calling other `kiflo()` methods | `ready`        |

## Full example: inject tracking code into a form

```javascript theme={null}
// 1. Extended snippet (in <head>)
var kjs = window.kjs || function (a) {
  var c = {
    apiKey: a.apiKey,
    callbacks: [],
    on: function(e, b) { c.callbacks.push([e, b]) }
  };
  var d = document;
  setTimeout(function () {
    var b = d.createElement("script");
    b.src = a.url || "https://cdn.kiflo.com/k.js", d.getElementsByTagName("script")[0].parentNode.appendChild(b)
  });
  return c;
}({ apiKey: "YOUR_API_KEY" });

// 2. Subscribe to the ready event (inline or in a separate script below the form)
kjs.on('ready', function(trackingCode) {
  var field = document.getElementById('kifloTrackingCode');
  if (field) {
    field.value = trackingCode || '';
  }
});
```

```html theme={null}
<!-- 3. Hidden field in your HTML form -->
<form id="signupForm" method="post" action="/signup">
  <input type="text"   name="email"    placeholder="Email" />
  <input type="hidden" id="kifloTrackingCode" name="kifloTrackingCode" value="" />
  <button type="submit">Sign Up</button>
</form>
```

When the form is submitted, `kifloTrackingCode` is included in the POST body. Pass its value to the [Kiflo REST API](https://docs-api.kiflo.com) from your server to attribute the new customer to the correct partner.
