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

# JavaScript API

> The window.loveful storefront bus: its properties, methods, share API, events, the Shopify customer events it publishes and what it keeps in browser storage.

Loveful's storefront script (`loveful.js`) is loaded by the Loveful app embed with `defer`. It reads the page's state from the HTML the embed prints, exposes a small bus on `window.loveful`, and defines the [web components](https://docs.loveful.app/developers/web-components.md).

> [!NOTE]
>
> The global is always lowercase: `window.loveful`. It exists only while the app embed is on.

## Waiting for the bus

Loveful fires `loveful:ready` on `document` once the bus is set up and, for a shopper who has just signed in, their guest items have moved to their account. Your script may load before or after Loveful's, so check for the bus first and listen for the event otherwise:

```js theme={null}
const onLoveful = (callback) => {
  if (window.loveful) window.loveful.ready.then(() => callback(window.loveful));
  else document.addEventListener("loveful:ready", (e) => callback(e.detail.loveful), { once: true });
};

onLoveful((loveful) => {
  console.log("Saved variants:", [...loveful.state]);
});
```

If the app embed is turned off, neither happens and the callback never runs.

`loveful.ready` resolves once a shopper who has just signed in has had their guest items moved to their account. For guests it resolves straight away. The examples below assume `const loveful = window.loveful` inside such a callback.

## Properties

| Property | Type | Description |
| - | - | - |
| `state` | `Set<string>` | Variant ids saved on the default list, as strings. |
| `snapshots` | `Map<string, LovefulSnapshot>` | Saved items' details, keyed by variant id, where the page knows them: a guest's items, and items saved during this session. |
| `productOf` | `Map<string, string>` | Each saved variant id's product id, where known. |
| `authenticated` | `boolean` | Whether a customer is signed in. |
| `ready` | `Promise<void>` | See [Waiting for the bus](#waiting-for-the-bus). |
| `tabId` | `string` | A random id for this tab, sent as `tab_id` in bus event details. |
| `i18n` | `Record<string, string>` | The storefront strings: the locale file's defaults with the merchant's translation overrides on top. |
| `share` | `object` | The [share API](#share-api). |

```js theme={null}
loveful.state.has("44012345678901"); // is this variant saved?
loveful.state.size;                  // how many items on the default list
loveful.authenticated;               // false for a guest
```

### LovefulSnapshot

The shape of a saved item in `snapshots` and in `item_added` events:

```ts theme={null}
interface LovefulSnapshot {
  variant_id: string;
  product_id: string;
  title: string;
  handle: string;
  image: string | null;
  price: string;    // major units, such as "45.00"
  currency: string; // ISO code
  available_for_sale: boolean;
  status: string;   // "ACTIVE" by default
  added_at: string; // ISO 8601
}
```

A signed-in shopper's items saved before this page load are in `state` but not in `snapshots`: their details were rendered by Liquid, not sent to the script.

## Methods

> [!WARNING]
>
> The bus has no add, remove or toggle method. Saving and removing are done by Loveful's elements: render a [`<loveful-button>`](https://docs.loveful.app/developers/web-components#loveful-button) for the product and let the shopper click it, and use the remove control on wishlist cards.

### productSaved

**productSaved(productId)** `boolean`

Whether any variant of the product is saved. Takes a product id as a string.

```js theme={null}
if (loveful.productSaved("8012345678901")) badge.textContent = "In your wishlist";
```

### snapshot

**snapshot(variantId)** `LovefulSnapshot | null`

The saved item's snapshot, or `null` when the page has none for it. Accepts a string or number.

```js theme={null}
const item = loveful.snapshot(44012345678901);
if (item) console.log(`${item.title} saved on ${new Date(item.added_at).toLocaleDateString()}`);
```

### clear

**clear(options?)** `Promise\<boolean\>`

Empties one of the shopper's lists. `options.list` is the list number, `1` (the default list, and a guest's only one) to `10`. Resolves `false` when the request fails, or when a guest asks for a list other than `1`. Clearing list 1 fires `item_removed` for each item, then one `list_cleared`.

```js theme={null}
const ok = await loveful.clear();             // the default list
const okList2 = await loveful.clear({ list: 2 });
```

### t

**t(key, fallback)** `string`

A storefront string from `i18n`, or `fallback` when the key is missing or empty.

```js theme={null}
button.textContent = loveful.t("loveful.save", "Save to wishlist");
```

Placeholders are left for you to fill: `%count%`, `%title%` or `%email%` in the defaults, or `{{ count }}` and the like in the merchant's overrides:

```js theme={null}
loveful
  .t("loveful.saved_count_other", "Saved by %count% shoppers")
  .replace(/%count%|\{\{\s*count\s*\}\}/g, "12");
```

### publishAnalytics

**publishAnalytics(event, detail)** `void`

Publishes a custom event to Shopify's customer events (`Shopify.analytics.publish`), for custom pixels to subscribe to. Does nothing where that API is unavailable.

```js theme={null}
loveful.publishAnalytics("loveful:wishlist_cta_clicked", { placement: "header" });
```

## Share API

Each method calls Loveful through the store's app proxy. `getToken`, `resetToken` and `email` need a signed-in shopper; `getList` works for anyone.

`share_url` is built on the shopper's current domain and language root, with the token in the `loveful_token` query parameter.

### share.getToken

**share.getToken()** `Promise\<\{ token, share_url \}\>`

The default list's share link, made on first use. Rejects when the request fails.

```js theme={null}
const { share_url } = await loveful.share.getToken();
await navigator.clipboard.writeText(share_url);
```

### share.resetToken

**share.resetToken()** `Promise\<\{ token, share_url \}\>`

A new share link. The old one stops working. Rejects when the request fails.

```js theme={null}
if (confirm("Your old link will stop working. Continue?")) {
  const { share_url } = await loveful.share.resetToken();
  input.value = share_url;
}
```

### share.getList

**share.getList(token)** `Promise\<LovefulSharedListResponse\>`

A shared list by its token. Rejects with `loveful.share.getList: not_found` when the token is unknown or was reset.

```js theme={null}
const token = new URLSearchParams(location.search).get("loveful_token");
try {
  const list = await loveful.share.getList(token);
  heading.textContent = `${list.owner ?? "Someone"}'s wishlist (${list.item_count})`;
} catch {
  heading.textContent = "This link no longer works";
}
```

```ts theme={null}
interface LovefulSharedListResponse {
  owner: string | null;
  token: string;
  item_count: number;
  items: Array<{
    variant_id: string;
    product_id: string;
    title: string;
    handle: string;
    image: string | null;
    price: string;
    currency: string;
    available_for_sale: boolean;
    status: string;
    added_at: string;
  }>;
}
```

### share.email

**share.email(\{ to, name, message? })** `Promise\<LovefulShareEmailResult\>`

Emails the wishlist to one address, in the shopper's language. Never rejects.

```js theme={null}
const result = await loveful.share.email({
  to: "friend@example.com",
  name: "Sam",
  message: "Birthday ideas",
});
if (result !== "ok") console.warn("Not sent:", result);
```

```ts theme={null}
type LovefulShareEmailResult =
  | "ok"
  | "limit_recipient" // already sent to this address today
  | "limit"           // the shopper's or the store's daily limit
  | "off"             // email sharing is turned off
  | "failed";
```

`<loveful-share-link>`'s email form shows each one in the merchant's words: `loveful.share_email_limit_recipient`, `loveful.share_email_limit`, `loveful.share_email_off` and `loveful.share_email_failed`.

## Bus events

`window.loveful` is an `EventTarget`. It dispatches `CustomEvent`s whenever the saved state changes, in this tab or in another tab of the same store (changes are relayed between tabs with a `BroadcastChannel` named `loveful`). `tab_id` is the tab the change was made in: compare it with `loveful.tabId` to tell local changes from relayed ones.

### item\_added

**detail** `\{ variant_id: string, snapshot: LovefulSnapshot, tab_id: string \}`

A variant was saved. `state`, `snapshots` and `productOf` are already updated.

```js theme={null}
loveful.addEventListener("item_added", (e) => {
  const { variant_id, snapshot } = e.detail;
  console.log(`Saved ${snapshot.title} (${variant_id})`);
});
```

### item\_removed

**detail** `\{ variant_id: string, tab_id: string \}`

A variant was removed. Also fired for each item when the default list is cleared.

```js theme={null}
loveful.addEventListener("item_removed", (e) => {
  document.querySelector(`[data-variant="${e.detail.variant_id}"]`)?.classList.remove("is-saved");
});
```

### list\_cleared

**detail** `\{ variant_ids: string[], tab_id: string \}`

The default list was emptied, after an `item_removed` for each of `variant_ids`.

```js theme={null}
loveful.addEventListener("list_cleared", (e) => {
  console.log(`Cleared ${e.detail.variant_ids.length} items`);
});
```

## Document events

### loveful:ready

Fired on `document` once, with `detail: { loveful }`. See [Waiting for the bus](#waiting-for-the-bus).

```js theme={null}
document.addEventListener("loveful:ready", (e) => {
  console.log("Loveful is ready for", e.detail.loveful.authenticated ? "a customer" : "a guest");
}, { once: true });
```

### Share events

[`<loveful-share-link>`](https://docs.loveful.app/developers/web-components#loveful-share-link) dispatches bubbling `CustomEvent`s on itself, so they can be caught on `document`:

| Event | `detail` |
| - | - |
| `loveful:share_link_copied` | `{ share_url }` when the link was already known, or `{ token, share_url }` when it was just made |
| `loveful:share_link_reset` | `{ token, share_url }` |
| `loveful:share_emailed` | none |

```js theme={null}
document.addEventListener("loveful:share_link_copied", (e) => {
  console.log("Copied", e.detail.share_url);
});

document.addEventListener("loveful:share_link_reset", (e) => {
  console.log("New link", e.detail.share_url);
});

document.addEventListener("loveful:share_emailed", () => {
  console.log("Wishlist emailed");
});
```

### Events Loveful listens for

The save button and the saved count follow the theme's variant picker. They listen on `document` for:

* `shopify:product:select`, Shopify's standard storefront event: the variant comes from the event's `promise`, which resolves with `{ variant }`.
* `variant:update`, `variant:change` and `change`: the variant id is read from `event.detail.variant.id` or `event.detail.resource.id` (a GID or a number), or else from the `?variant=` URL parameter a tick later.

A theme with a custom picker can dispatch one of these to keep Loveful in step:

```js theme={null}
document.dispatchEvent(
  new CustomEvent("variant:change", { detail: { variant: { id: 44012345678901 } } }),
);
```

## Shopify customer events

Loveful publishes these through `Shopify.analytics.publish`, so a custom pixel can subscribe to them. They are published only in the tab where the change was made.

| Event | Data | Published when |
| - | - | - |
| `loveful:item_added` | `{ variant_id, product_id, item_count }` | An item is saved |
| `loveful:item_removed` | `{ variant_id, product_id, item_count }` | An item is removed |
| `loveful:list_cleared` | `{ item_count }` | The default list is cleared |
| `loveful:variant_changed` | `{ from_variant_id, to_variant_id, product_id }` | A wishlist card's options are changed |
| `loveful:wishlist_page_viewed` | `{ item_count }` | A `<loveful-list>` is set up |
| `loveful:share_viewed` | `{ share_token, item_count }` | A `<loveful-shared-list>` loads a list |

```js Custom pixel theme={null}
analytics.subscribe("loveful:item_added", (event) => {
  const { variant_id, product_id, item_count } = event.customData;
  // send to your analytics tool
});

analytics.subscribe("loveful:item_removed", (event) => {
  const { variant_id, item_count } = event.customData;
});

analytics.subscribe("loveful:list_cleared", (event) => {
  const { item_count } = event.customData; // how many were removed
});

analytics.subscribe("loveful:variant_changed", (event) => {
  const { from_variant_id, to_variant_id } = event.customData;
});

analytics.subscribe("loveful:wishlist_page_viewed", (event) => {
  const { item_count } = event.customData;
});

analytics.subscribe("loveful:share_viewed", (event) => {
  const { share_token, item_count } = event.customData;
});
```

## Data attributes on cards

Wishlist cards (`li.loveful-card`) carry `data-variant-id` and `data-handle`. While a card's options are being changed it also carries `data-swap-to` with the new variant id.

## Storage

| Key | Storage | Holds |
| - | - | - |
| `loveful.v1.items` | `localStorage` | A guest's saved items (snapshots), moved to their account when they sign in. |
| `loveful.v1.pending` | `sessionStorage` | Changes the server confirmed in the last two minutes, laid over the page until Shopify's metafields catch up. |
| `loveful.v1.share_token` | `sessionStorage` | A share token made or reset in the last five minutes. |
| `loveful.v1.share_attr` | `sessionStorage` | The value last written to the cart's `_loveful_share` attribute. |

Opening a shared wishlist with items sets the hidden cart attribute `_loveful_share` to the share token (or `<token>:<send id>` when opened from a share email), so an order can be traced back to the share.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.