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

# Usage

> Below is the full list of commands to call the Cello Attribution JS SDK with.

## Script Initialization and Timing

The attribution script loads asynchronously. To avoid race conditions between script loading and your application calls, you have two options:

### Option 1: Queue Function (Recommended)

Add this JavaScript code before any calls to the library to queue commands until the script loads:

```javascript expandable theme={null}
window.CelloAttribution=window.CelloAttribution||function(t,...o){if("getReferral"===t)throw new Error("getReferral is not supported in this context. Use getUcc instead.");let e,n;const i=new Promise((t,o)=>{e=t,n=o});return window.CelloAttributionCmd=window.CelloAttributionCmd||[],window.CelloAttributionCmd.push({command:t,args:o,resolve:e,reject:n}),i}
```

### Option 2: Wait for Script Initialization

Alternatively, wait for the script to load before making calls:

```javascript theme={null}
document.addEventListener('DOMContentLoaded', async function() {
    // Wait for script initialization
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    if (typeof window.CelloAttribution === 'function') {
        // Now safe to call methods
        const ucc = await window.CelloAttribution("getUcc");
        console.log('UCC:', ucc);
    } else {
        console.error('Cello Attribution script failed to load');
    }
});
```

## `attachTo(formElement)`

Attaches hidden input to the passed `HTMLFormElement` node, or array of nodes.

```javascript theme={null}
window.CelloAttribution("attachTo", formElement);
```

### Accepts

**formElement** `HTMLFormElement | HTMLFormElement[]` *required*

Form(s) to attach the hidden input to

### Example

```javascript theme={null}
window.CelloAttribution("attachTo", document.querySelector("form"));
```

***

## `getCampaignConfig()`

Returns campaign configuration for new users, including discount information.

```javascript theme={null}
const campaignConfig = await window.CelloAttribution("getCampaignConfig");
```

### Returns

**campaignConfig** `object`

The campaign config object:

**properties**

**newUserDiscountMonth** `number`

Duration of discount in months (e.g., 12 for 12 months)

**newUserDiscountPercentage** `number`

Discount as decimal format (0.1 = 10%, 0.25 = 25%)

### Complete Example

```javascript theme={null}
const config = await window.CelloAttribution("getCampaignConfig");
console.log(config);
// Output:
// {
//   newUserDiscountPercentage: 0.1,    // 10% discount
//   newUserDiscountMonth: 12           // For 12 months
// }

// Convert to display format:
const displayPercentage = config.newUserDiscountPercentage * 100; // 10
const message = `${displayPercentage}% off for ${config.newUserDiscountMonth} months`;
console.log(message); // "10% off for 12 months"

// Use in your UI:
document.getElementById('discount-banner').innerHTML = 
  `🎉 Special offer: ${displayPercentage}% off your first ${config.newUserDiscountMonth} months!`;
```

## `getReferrerName()`

Returns the referrer's name, if provided in the referral link.

```javascript theme={null}
const name = await window.CelloAttribution("getReferrerName");
```

### Returns

**name** `string | undefined`

Referrer's name or `undefined`

## `getUcc()`

Retrieves the referral code `ucc` from the URL or the cookie (if cookies are enabled).

```javascript theme={null}
const ucc = await window.CelloAttribution("getUcc");
```

### Returns

**ucc** `string`

Unique campaign code/referral code

## ~~`attachAll()`~~

> ⚠️ **Deprecated**: forms are now auto-detected and the hidden `ucc` input is injected automatically.
> Use [`attachTo(formElement)`](#attachto-formelement) for targeted cases instead.

**more**

```javascript theme={null}
window.CelloAttribution("attachAll");
```

***

## Troubleshooting

### Attribution Script Not Loading

```javascript theme={null}
// Check if script loaded correctly
if (typeof window.CelloAttribution !== 'function') {
    console.error('Cello Attribution script failed to load');
    // Implement fallback logic
    // For example, proceed without attribution or show error message
}
```

### Methods Returning undefined or null

**Common causes:**

* Script not fully initialized - wait for DOM load or use the queue function
* Incorrect method syntax - ensure you use `window.CelloAttribution("methodName")`
* No referral data available - user didn't come from a referral link

**Solutions:**

```javascript theme={null}
// Always check return values
const ucc = await window.CelloAttribution("getUcc");
if (ucc) {
    console.log('Referral code found:', ucc);
} else {
    console.log('No referral code - user came directly');
}

// Handle missing referrer names gracefully
const referrerName = await window.CelloAttribution("getReferrerName");
const greeting = referrerName 
    ? `Welcome! ${referrerName} referred you` 
    : 'Welcome to our platform';
```

### Testing Attribution Methods

Test all methods in your browser console:

```javascript theme={null}
// Test UCC retrieval
await window.CelloAttribution("getUcc");
// Returns: string (referral code) or null

// Test referrer name
await window.CelloAttribution("getReferrerName");
// Returns: string (referrer name) or undefined

// Test campaign config
await window.CelloAttribution("getCampaignConfig");
// Returns: { newUserDiscountPercentage: number, newUserDiscountMonth: number }
```

### Network and Loading Issues

```javascript theme={null}
// Check if attribution script is blocked
fetch('https://assets.cello.so/attribution/latest/cello-attribution.js')
  .then(response => {
    if (!response.ok) {
      console.error('Attribution script blocked or unavailable');
    }
  })
  .catch(error => {
    console.error('Network error loading attribution script:', error);
  });
```

### Common Integration Patterns

```javascript theme={null}
// Safe attribution check with fallbacks
async function initializeWithAttribution() {
    try {
        // Wait for script if needed
        let retries = 0;
        while (typeof window.CelloAttribution !== 'function' && retries < 10) {
            await new Promise(resolve => setTimeout(resolve, 500));
            retries++;
        }
        
        if (typeof window.CelloAttribution === 'function') {
            const ucc = await window.CelloAttribution("getUcc");
            const referrerName = await window.CelloAttribution("getReferrerName");
            const campaignConfig = await window.CelloAttribution("getCampaignConfig");
            
            return { ucc, referrerName, campaignConfig };
        } else {
            throw new Error('Attribution script not available');
        }
    } catch (error) {
        console.warn('Attribution initialization failed:', error);
        return { ucc: null, referrerName: null, campaignConfig: null };
    }
}

// Use in your application
initializeWithAttribution().then(({ ucc, referrerName, campaignConfig }) => {
    // Proceed with or without attribution data
    if (ucc) {
        console.log('Referral detected:', { ucc, referrerName, campaignConfig });
    }
});
```

***

## ~~`getReferral()`~~

> ⚠️ **Deprecated**: use [`getUcc()`](#getucc) instead.

**more**

```javascript theme={null}
const ucc = window.CelloAttribution("getReferral");
```

### Returns

**ucc** `string`

Unique campaign code/referral code


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