# Browser SDK

Source: https://gokarla.io/docs/platform/browser-sdk

import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';

# Browser SDK

The GoKarla Browser SDK is a lightweight JavaScript library that enables seamless integration of GoKarla's tracking and resolution features into your website. With just a few lines of code, you can embed order tracking, order finding, and resolution workflows directly into your customer experience.

## Features

- **Zero Dependencies**: Pure JavaScript implementation with no external dependencies
- **Universal Compatibility**: UMD format works with all modern browsers and build systems
- **Responsive Design**: Automatically adapts iframe heights for desktop and mobile devices
- **Multiple Entry Points**: Support for order tracking, order finder, and resolution workflows
- **W3C Compliant**: Supports both standard `data-` attributes and legacy formats
- **Minimal Bundle Size**: Optimized for fast loading with < 10KB minified

## Installation

Add the GoKarla Browser SDK to your website using our CDN:

```html title="Quick Setup"
<script
  src="https://browser.gokarla.io/latest/bundle.min.js"
  id="karla-bundle"
  data-shop-slug="your-shop-slug"
></script>
```

### Version Management

We recommend using the `latest` version if you want to receive automatically the latest updates, we ensure backwards compatibility for stable versions:

```html title="Versioned Installation"
<!-- Latest version -->
<script src="https://browser.gokarla.io/latest/bundle.min.js"></script>

<!-- Specific version -->
<script src="https://browser.gokarla.io/0.0.8/bundle.min.js"></script>
```

## Basic Configuration

### Minimal Setup

The simplest integration requires only your shop slug and a container div:

```html title="Minimal Configuration"
<div id="karla-container"></div>

<script
  src="https://browser.gokarla.io/latest/bundle.min.js"
  id="karla-bundle"
  data-shop-slug="your-shop-slug"
></script>
```

### Full Configuration

Configure all available options for complete control:

```html title="Full Configuration Example"
<div id="karla-container"></div>

<script
  src="https://browser.gokarla.io/latest/bundle.min.js"
  id="karla-bundle"
  data-shop-slug="your-shop-slug"
  data-order-number="12345"
  data-zip-code="10119"
  data-token="eyJhbGciOi..."
  data-starter-page="order-tracking"
  data-debug="true"
></script>
```

## Configuration Options

### Required Attributes

| Attribute        | Type   | Description                                     |
| ---------------- | ------ | ----------------------------------------------- |
| `data-shop-slug` | string | Your unique shop identifier provided by GoKarla |

### Optional Attributes

| Attribute           | Type    | Default          | Description                                                               |
| ------------------- | ------- | ---------------- | ------------------------------------------------------------------------- |
| `data-order-number` | string  | URL param        | Pre-fill order number for tracking                                        |
| `data-zip-code`     | string  | URL param        | Pre-fill ZIP code for validation                                          |
| `data-token`        | string  | URL param        | Secure order-specific token for direct access (skips ZIP code validation) |
| `data-order-name`   | string  | URL param        | Alternative order identifier (e.g. shop display name)                     |
| `data-external-id`  | string  | URL param        | External order ID from a third-party system                               |
| `data-order-id`     | string  | URL param        | Internal GoKarla order ID                                                 |
| `data-lang`         | string  | URL param        | [ISO 639-1](https://en.wikipedia.org/wiki/ISO_639-1) language code        |
| `data-starter-page` | string  | `order-tracking` | Initial page to display                                                   |
| `data-debug`        | boolean | `false`          | Enable debug logging                                                      |

### Starter Page Options

<Tabs>
<TabItem value="order-tracking" label="Order Tracking" default>

```html title="Order Tracking Page"
<script
  data-starter-page="order-tracking"
  data-shop-slug="your-shop-slug"
  ...
></script>
```

Displays the order tracking interface where customers can view their shipment status.

</TabItem>
<TabItem value="resolve" label="Resolution Center">

```html title="Resolution Center"
<script
  data-starter-page="resolve"
  data-shop-slug="your-shop-slug"
  ...
></script>
```

Opens the resolution workflow for returns, exchanges, or other post-purchase requests.

</TabItem>
<TabItem value="finder" label="General Finder">

```html title="General Finder"
<script data-starter-page="finder" data-shop-slug="your-shop-slug" ...></script>
```

Shows a form where customers can search for their orders using order number and ZIP code.

</TabItem>
<TabItem value="tracking-updates" label="Tracking Updates">

```html title="Tracking Updates"
<script
  data-starter-page="tracking-updates"
  data-shop-slug="your-shop-slug"
  ...
></script>
```

Shows only the tracking updates widget.

</TabItem>
<TabItem value="global" label="Global">

```html title="Global Scope"
<script
  data-starter-page="global"
  data-shop-slug="your-shop-slug"
  defer
></script>
```

Enables global functionality, like attribution tracking across all pages. See [Attribution Tracking](#attribution-tracking-shopify) for complete details.

</TabItem>
</Tabs>

## Integration Methods

:::important DOM Order Requirement
The container element **must exist in the DOM before the script loads**. The SDK executes immediately upon loading and looks for the `karla-container` div. If it doesn't exist yet, the SDK will fail to initialize.
:::

### Method 1: Standard Integration (Recommended)

Let the SDK handle all iframe configuration:

```html title="Standard Integration"
<div id="karla-container"></div>

<script
  src="https://browser.gokarla.io/latest/bundle.min.js"
  id="karla-bundle"
  data-shop-slug="your-shop-slug"
></script>
```

:::tip Why use karla-container?
This is the simplest and most future-proof approach. The SDK automatically handles all iframe configuration, security settings, and dynamic height management.
:::

### Method 2: Custom Iframe (More Control)

For advanced use cases where you need more control over the iframe element:

```html title="Custom Iframe Integration"
<iframe
  id="karla-frame"
  style="width: 100%; border: none;"
  title="GoKarla Tracking"
></iframe>

<script
  src="https://browser.gokarla.io/latest/bundle.min.js"
  id="karla-bundle"
  data-shop-slug="your-shop-slug"
></script>
```

:::info When to use custom iframe
Use this approach when you need:

- Custom iframe attributes or styling
- Integration with specific frameworks
- Control over iframe lifecycle
- Compatibility with legacy implementations

:::

### Method 3: Dynamic Parameters

Pass order information from your backend:

```html title="Server-Side Integration"
<!-- Example with PHP (token-based) -->
<script
  src="https://browser.gokarla.io/latest/bundle.min.js"
  id="karla-bundle"
  data-shop-slug="your-shop-slug"
  data-order-number="<?php echo $order->number; ?>"
  data-token="<?php echo $order->tracking_token; ?>"
></script>

<!-- Example with PHP (ZIP code-based) -->
<script
  src="https://browser.gokarla.io/latest/bundle.min.js"
  id="karla-bundle"
  data-shop-slug="your-shop-slug"
  data-order-number="<?php echo $order->number; ?>"
  data-zip-code="<?php echo $order->zip; ?>"
></script>

<!-- Example with JavaScript -->
<script>
  // Add attributes dynamically
  document.addEventListener("DOMContentLoaded", function () {
    const script = document.getElementById("karla-bundle");
    script.setAttribute("data-order-number", orderData.number);
    script.setAttribute("data-token", orderData.trackingToken);
  });
</script>
```

## Advanced Configuration

### Custom Window Configuration

Control the behavior through the global `KARLA_CONFIG` object:

```javascript title="Advanced Configuration"
<script>
  window.KARLA_CONFIG = {
    hideHeader: true,        // Hide the GoKarla header
    hideAllWidgets: false,   // When true, only the tracking events widget is shown — order summary, delivery address, tracking number, reviews, deals, agent, notification banner and all promotion slots are hidden
  };
</script>

<!-- Container must be present first -->
<div id="karla-container"></div>

<script
  src="https://browser.gokarla.io/latest/bundle.min.js"
  id="karla-bundle"
  data-shop-slug="your-shop-slug"
></script>
```

### Debug Mode

Enable debug mode to troubleshoot integration issues:

```html title="Debug Mode"
<div id="karla-container"></div>

<script
  src="https://browser.gokarla.io/latest/bundle.min.js"
  id="karla-bundle"
  data-shop-slug="your-shop-slug"
  data-debug="true"
></script>
```

Debug mode logs:

- Configuration details
- URL construction
- Height adjustments
- Event communications

## URL Parameter Support

The SDK automatically reads URL parameters as fallbacks when `data-*` script attributes are not set:

```javascript title="URL Parameter Mapping"
// URL: https://yoursite.com/tracking?orderNumber=12345&zipCode=10119&lang=de

// These parameters are automatically detected:
// - orderNumber → data-order-number
// - zipCode → data-zip-code
// - token → data-token
// - orderName → data-order-name
// - externalId → data-external-id
// - orderId → data-order-id
// - lang → Language preference
// - flowType → Resolution flow type (for resolve page)
```

:::note
This configuration is very often used in public links
:::

### Order lookup methods

The SDK supports multiple ways to identify an order. The tracking and resolve pages will use whichever identifiers are provided:

| Method                  | Parameters                              | Use case                                       |
| ----------------------- | --------------------------------------- | ---------------------------------------------- |
| Order number + ZIP code | `orderNumber` + `zipCode`               | Standard lookup, customer provides both values |
| Token-based access      | `token` (+ `orderNumber`)               | Secure direct access via a pre-generated link  |
| Alternative identifiers | `orderName`, `externalId`, or `orderId` | Lookup by alternative order references         |

:::tip Recommended: token-based access
Token-based lookup is the most secure option for pre-built tracking links
(e.g. in shipping confirmation emails). Each token is unique to an order and
cannot be guessed or enumerated.

**You can disable ZIP code lookup entirely and rely on tokens alone.** Go to
your shop settings in the [portal](https://portal.gokarla.io/) and enforce
token-based access as the only allowed lookup method. Customers then reach
the tracking page exclusively through the links you send them — no ZIP code
entry, no order finder, no way for a bad actor to brute-force access to an
order.
:::

:::info
These additional parameters (`token`, `orderName`, `externalId`, `orderId`) are only forwarded to **track** and **resolve** pages. The **finder** page only receives the `lang` parameter, as it has its own order search form.
:::

All lookup methods are protected against enumeration attacks. Invalid or mismatched parameters result in a generic response that does not reveal whether an order exists.

## Migration Guide

### From Legacy Attributes

If you're using non-W3C compliant attributes, migrate to the standard format:

<Tabs>
<TabItem value="before" label="Before (Legacy)">

```html
<script
  id="karla-bundle"
  shop-slug="your-shop-slug"
  starter-page="order-tracking"
  debug
></script>
```

</TabItem>
<TabItem value="after" label="After (W3C Compliant)">

```html
<script
  id="karla-bundle"
  data-shop-slug="your-shop-slug"
  data-starter-page="order-tracking"
  data-debug="true"
></script>
```

</TabItem>
</Tabs>

### Attribute Reference

| Legacy Attribute | W3C Compliant       | Notes                   |
| ---------------- | ------------------- | ----------------------- |
| `shop-slug`      | `data-shop-slug`    | Required                |
| `starter-page`   | `data-starter-page` | Set to "order-tracking" |
| `debug`          | `data-debug`        | Set to "false"          |
| `order-number`   | `data-order-number` | Optional                |
| `zip-code`       | `data-zip-code`     | Optional                |
| —                | `data-token`        | Optional (new)          |
| —                | `data-order-name`   | Optional (new)          |
| —                | `data-external-id`  | Optional (new)          |
| —                | `data-order-id`     | Optional (new)          |
| —                | `data-lang`         | Optional (new)          |

## Best Practices

### 1. Load Timing

```html title="Optimal Load Timing"
<!-- Load SDK after page content for better performance -->
<body>
  <!-- Your page content -->

  <div id="karla-container"></div>

  <!-- Load SDK at the end of body -->
  <script
    src="https://browser.gokarla.io/latest/bundle.min.js"
    id="karla-bundle"
    data-shop-slug="your-shop-slug"
    async
  ></script>
</body>
```

### 2. Container Styling

```css title="Recommended Container Styles"
/* Ensure proper container sizing */
#karla-container {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

/* The SDK handles iframe creation and styling automatically */
```

### 3. Error Handling

```javascript title="Error Handling"
<script>
  // Listen for SDK errors
  window.addEventListener('error', function(e) {
    if (e.target && e.target.id === 'karla-bundle') {
      console.error('Failed to load GoKarla SDK');
      // Implement fallback logic
    }
  });
</script>
```

### 4. Content Security Policy

If using CSP headers, allow the GoKarla domains:

```http title="CSP Configuration"
Content-Security-Policy:
  script-src 'self' https://browser.gokarla.io;
  frame-src 'self' https://app.gokarla.io;
  connect-src 'self' https://api.gokarla.io;
```

## Troubleshooting

### Common Issues

<details>
<summary>**Iframe not displaying**</summary>

1. Verify your shop slug is correct
2. Check browser console for errors
3. Ensure the script has `id="karla-bundle"`
4. Confirm container element exists (`id="karla-container"` or `id="karla-frame"`)

</details>

<details>
<summary>**Height not adjusting properly**</summary>

1. The SDK automatically manages heights
2. Ensure no conflicting CSS on the iframe
3. Check if JavaScript errors prevent height updates
4. Enable debug mode to see height calculations

</details>

<details>
<summary>**Order data not pre-filling**</summary>

1. Verify attribute names are correct (`data-order-number`, not `order-number`)
2. Check URL parameters as fallback
3. Ensure values are properly encoded
4. Enable debug mode to see parameter parsing

</details>

<details>
<summary>**Page showing multiple errors or not loading**</summary>

If the tracking page displays multiple errors or fails to load:

1. Wait a few minutes before trying again
2. Avoid making rapid repeated requests
3. Check your implementation isn't triggering multiple loads
4. Ensure you're not automatically refreshing the page
5. If the issue persists after waiting, contact support

This typically occurs when our system detects unusual activity patterns.

</details>

<details>
<summary>**Order finder shows instead of tracking page**</summary>

If you see the order finder form when expecting the tracking page:

1. Verify the order number and ZIP code are correct
2. Ensure the order exists in the system
3. Check that order data has been synchronized
4. Confirm the parameters are being passed correctly
5. Try again after a few minutes if the order was just placed

The system displays the order finder when it cannot locate the specified order or encounters an error during lookup. This is obfuscated by design, to prevent order enumeration attacks.

</details>

<details>
<summary>**Order finder fails to locate order**</summary>

If the order finder cannot find your order after submitting:

1. Double-check the order number format and ZIP code
2. Ensure the order exists and has been processed
3. Verify the ZIP code matches the shipping address
4. Wait a few minutes if the order was recently placed
5. Check for any special characters or spaces in the order number

The same security mechanism that shows the order finder instead of the tracking page also prevents the finder from revealing whether an order exists when incorrect details are provided.

</details>

### Debug Checklist

1. **Script Loading**

   ```javascript
   // Check if SDK loaded
   console.log(document.getElementById("karla-bundle"));
   ```

2. **Configuration**

   ```javascript
   // View current configuration (in debug mode)
   window.KARLA_CONFIG;
   ```

3. **Network Requests**
   - Check browser Network tab
   - Verify requests to `app.gokarla.io`
   - Ensure no CORS errors

## Security Considerations

### Data Handling

- Order numbers and ZIP codes are transmitted securely over HTTPS
- No sensitive payment information is handled by the SDK
- All data is processed according to GDPR requirements

### Abuse Prevention

GoKarla implements multiple security measures to protect merchant and customer data:

- **Rate Limiting**: Excessive requests from a single source may be temporarily restricted
- **Order Enumeration Protection**: The system intentionally provides generic responses to prevent discovering valid order numbers
- **Activity Monitoring**: Suspicious patterns are automatically detected and may result in access restrictions
- **IP-based Protection**: Sources exhibiting abusive behavior may be blocked

If you're implementing automated testing or monitoring, please:

- Use reasonable request intervals
- Contact support for proper API access if needed
- Avoid attempts to enumerate or discover order information

Violations of these security measures may result in permanent access restrictions.

### Iframe Sandboxing

The SDK automatically applies appropriate sandbox attributes when creating the iframe:

- `allow-same-origin`
- `allow-scripts`
- `allow-forms`
- `allow-modals`
- `allow-popups`
- Clipboard permissions: `clipboard-read clipboard-write`
- Fullscreen support

## Browser Support

| Browser        | Minimum Version |
| -------------- | --------------- |
| Chrome         | 90+             |
| Firefox        | 88+             |
| Safari         | 14+             |
| Edge           | 90+             |
| Mobile Safari  | iOS 14+         |
| Chrome Android | 90+             |

## Performance

### Bundle Size

- **Minified**: < 10KB
- **Gzipped**: < 4KB
- **Zero runtime dependencies**

### Loading Strategy

```html title="Performance Optimization"
<!-- Async loading -->
<script async src="https://browser.gokarla.io/latest/bundle.min.js"></script>

<!-- Defer loading -->
<script defer src="https://browser.gokarla.io/latest/bundle.min.js"></script>

<!-- Preconnect for faster loading -->
<link rel="preconnect" href="https://browser.gokarla.io" />
<link rel="preconnect" href="https://app.gokarla.io" />
```

## Support

### Getting Help

- **Documentation**: [gokarla.io/docs](https://gokarla.io/docs)
- **Support**: support@gokarla.io
- **Status Page**: [status.gokarla.io](https://status.gokarla.io)

### Reporting Issues

When reporting issues, please include:

1. Your shop slug
2. Browser and version
3. Console errors (if any)
4. Network requests (HAR file if possible)
5. Steps to reproduce
