> For the complete documentation index, see [llms.txt](https://docs.caf.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.caf.io/caf-sdk/web-javascript/getting-started/document-detector/methods.md).

# SDK methods

This section provides detailed documentation for each SDK method. Scroll down to learn more about how to use each method, including their parameters, usage examples, and important notes.

* [initialize](#eiseg7yo37mw)
* [capture](#bxk99swpyysw)
* [close](#v4tuya2p9r40)
* [dispose](#vgby31evws8u)
* [isSupported](#zwx6320kaxha)
* [getIsInitialized](#g928mzquhg70)
* [loadAiModel](#mbpywqujzmy8)

## initialize <a href="#eiseg7yo37mw" id="eiseg7yo37mw"></a>

The `initialize` method is used to initialize the SDK. This method sets up internal variables and downloads the necessary resources for the SDK to function.

**Important**

* The initialization process can take a few seconds. It is recommended to call this function as early as possible in your flow to ensure a smooth user experience.

**Handling initialization errors**

Errors that can occur during the `initialize()` method:

| Error Name              | Description                                                                           |
| ----------------------- | ------------------------------------------------------------------------------------- |
| CafSdkInitError         | An error occurred during the SDK initialization.                                      |
| CafSdkUnauthorizedError | Unauthorized access to the SDK. Check if the token provided is valid and not expired. |

**Example**

```javascript
try {
  await sdk.initialize();
  console.log("SDK initialized successfully!");
} catch (error) {
  switch (error.name) {
    case "CafSdkInitError":
      console.error("SDK initialization error:", error.message);
      break;
    case "CafSdkUnauthorizedError":
      console.error("Unauthorized error:", error.message);
      break;
    default:
      console.error("Unexpected init error:", error.name, error.message);
  }
}
```

[Go back to the top](#cyrigz6p85t0)

## capture <a href="#bxk99swpyysw" id="bxk99swpyysw"></a>

The `capture` method is used to load the SDK onto the screen and perform document capture. It initializes the video stream (requesting permissions if needed) and loads it into the container.

For more information on input parameters and output results, refer to the lists below:

### Input

The `capture` method takes one parameter:

```javascript
const captureResult = await documentDetector.capture(options);
```

This parameter is an object containing the capture options. The following table lists the available capture options:

<table data-header-hidden><thead><tr><th width="368"></th><th></th><th></th><th></th></tr></thead><tbody><tr><td><strong>Parameter</strong></td><td><strong>Type</strong></td><td><strong>Required?</strong></td><td><strong>Default Value</strong></td></tr><tr><td><p><strong><code>expectedDocument</code></strong></p><p>Type and side of the document expected to be detected by the SDK. If value is <code>"any"</code> then any type of document will be accepted.</p></td><td><code>"rg_front" | "rg_back" | "rg_full" | "cnh_front" | "cnh_back" | "cnh_full" | "crlv" | "rne_front" | "rne_back" | "passport" | "ctps_front" | "ctps_back" | "any"</code></td><td>Yes.</td><td>-</td></tr><tr><td><p><strong><code>mode</code></strong></p><p>The capture mode. Can be <code>"automatic"</code>, <code>"manual"</code> or <code>"upload"</code>.</p><p>If the option <code>enableFramingAnalyzer</code> was manually set to <code>false</code>, the capture mode will be forced to <code>manual</code> regardless of the value passed in this parameter.</p></td><td><code>"automatic" | "manual" | "upload"</code></td><td>Yes.</td><td>-</td></tr><tr><td><p><strong><code>automaticCaptureMaxDuration</code></strong></p><p>The maximum duration in seconds for the automatic capture. If the duration is exceeded, the manual capture will be triggered.</p></td><td>number</td><td>No.</td><td><strong><code>60</code></strong></td></tr><tr><td><p><strong><code>uploadFileType</code></strong></p><p>The type of the file to be uploaded. The value can be <code>"IMAGE"</code>, <code>"PDF"</code> or <code>undefined</code>. If the value is <code>undefined</code>, both image and PDF files can be uploaded.</p></td><td><code>"IMAGE" | "PDF" | undefined</code></td><td>No.</td><td>Both <code>"IMAGE"</code> and <code>"PDF"</code>.</td></tr><tr><td><p><strong><code>personID</code></strong></p><p>The ID of the person (used for tracking purposes).</p></td><td>string</td><td>No.</td><td><code>undefined</code></td></tr><tr><td><p><strong><code>forceEndWhenInvalid</code></strong></p><p>Determines whether the capture should be forcefully finished when it is invalid.</p></td><td>boolean</td><td>No.</td><td><code>false</code></td></tr></tbody></table>

### Output

The `capture()` method returns a **signed JWT string** (`signedResponse`) from the backend. This JWT encodes all capture metadata and can be verified server-side. To access the capture details on the client side, decode the JWT payload.

```javascript
const signedResponse = await documentDetector.capture(options);
```

#### JWT Payload Fields

The decoded JWT payload contains the following fields:

| Field                          | Type            | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| ------------------------------ | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **`captures`**                 | `Array<object>` | List of captured document sides. Contains one entry for single-side or full-document captures.                                                                                                                                                                                                                                                                                                                                                                         |
| **`captures[0].scannedLabel`** | `string`        | The detected document model label, combining type and side. Possible values: `"rg_front"`, `"rg_back"`, `"rg_full"`, `"rg_new_front"`, `"rg_new_back"`, `"rg_new_full"`, `"cnh_front"`, `"cnh_back"`, `"cnh_full"`, `"new_cnh_front"`, `"new_cnh_back"`, `"new_cnh_full"`, `"crlv"`, `"new_crlv"`, `"rne_front"`, `"rne_back"`, `"rnm_front"`, `"rnm_back"`, `"passport_full"`, `"ctps_front"`, `"ctps_back"`, `"cin_front"`, `"cin_back"`, `"cin_full"`, `"generic"`. |
| **`captures[0].imageUrl`**     | `string`        | Pre-signed URL to the captured image stored on S3. This URL is temporary and expires after a few hours.                                                                                                                                                                                                                                                                                                                                                                |
| **`documentType`**             | `string`        | The detected document type in uppercase. Possible values: `"CNH"`, `"NEW_CNH"`, `"RG"`, `"RG_NOVO"`, `"CRLV"`, `"NEW_CRLV"`, `"RNE"`, `"RNM"`, `"PASSPORT"`, `"CTPS"`, `"CIN"`, `"OUTROS"`.                                                                                                                                                                                                                                                                            |
| **`trackingId`**               | `string`        | The tracking identifier for the capture session. It may be empty if not applicable.                                                                                                                                                                                                                                                                                                                                                                                    |
| **`iat`**                      | `number`        | JWT "issued at" timestamp (Unix epoch in seconds). Indicates when the token was generated.                                                                                                                                                                                                                                                                                                                                                                             |

#### JWT Payload Example

(e.g., front of CNH):

```json
{
  "captures": [
    {
      "scannedLabel": "new_cnh_front",
      "imageUrl": "https://example-url/image.jpg?signature..."
    }
  ],
  "documentType": "NEW_CNH",
  "trackingId": "",
  "iat": 1781646936
}
```

{% hint style="info" %}
The `signedResponse` JWT should be sent to your backend for server-side validation. Client-side decoding is only intended for display or logging purposes — do not rely on it for security decisions.
{% endhint %}

**Handling capture errors**

| Error Name                     | Description                                                              |
| ------------------------------ | ------------------------------------------------------------------------ |
| CafSdkCaptureError             | An error occurred during the capture process.                            |
| CafSdkCanceledError            | SDK run canceled by the user.                                            |
| CafInvalidOptionsError         | SDK capture options are invalid. Review the options provided to the SDK. |
| CafSdkBlockedError             | SDK capture has been blocked.                                            |
| CafUnsupportedError            | SDK capture is not supported for the specific document type.             |
| CafCameraPermissionError       | Error getting camera permission.                                         |
| CafCameraPermissionDeniedError | Camera permission denied by the user.                                    |
| CafCameraUnsupportedError      | Camera is not supported by the browser/device.                           |

**Example**

```javascript
try {
  // Load the SDK onto the screen and perform document capture.
  // Returns a JWT string containing the signed response with capture metadata.
  const signedResponse = await documentDetector.capture({
    expectedDocument: "cnh_front",
    mode: "automatic",
    automaticCaptureMaxDuration: 30,
    personID: "my-person-id",
  });
  
  // Decode the JWT to extract capture details
  const result = decodeJwt(signedResponse);

} catch (error) {
  switch (error.name) {
    case "CafSdkCaptureError":
      console.error("SDK capture error:", error.message);
      break;
    case "CafSdkCanceledError":
      console.error("Capture canceled by user:", error.message);
      break;
    case "CafInvalidOptionsError":
      console.error("Options error:", error.message);
      break;
    case "CafSdkBlockedError":
      console.error("SDK blocked error:", error.message);
      break;
    case "CafUnsupportedError":
      console.error("Unsupported error:", error.message);
      break;
    case "CafCameraPermissionError":
      console.error("General camera permission error:", error.message);
      break;
    case "CafCameraPermissionDeniedError":
      console.error("Camera permission denied error:", error.message);
      break;
    case "CafCameraUnsupportedError":
      console.error("Camera not supported error:", error.message);
      break;
    default:
      console.error("Unexpected capture error:", error.name, error.message);
  }
}
```

[Go back to the top](#cyrigz6p85t0)

## close <a href="#v4tuya2p9r40" id="v4tuya2p9r40"></a>

The `close` method is used to remove the SDK from the screen, removing its visual elements from the DOM.

**Handling close errors**

| Error Name       | Description                              |
| ---------------- | ---------------------------------------- |
| CafSdkCloseError | An error occurred while closing the SDK. |

**Example**

```javascript
try {
  await sdk.close();
} catch (error) {
  switch (error.name) {
    case "CafSdkCloseError":
      console.error("SDK close error:", error.message);
      break;
    default:
      console.error("Unexpected close error:", error.name, error.message);
  }
}
```

[Go back to the top](#cyrigz6p85t0)

## dispose <a href="#vgby31evws8u" id="vgby31evws8u"></a>

The `dispose` method is used to de-initialize the SDK. It stops the video stream and clears the SDK's internal variables.

**Handling dispose errors**

| Error Name         | Description                                |
| ------------------ | ------------------------------------------ |
| CafSdkDisposeError | An error occurred while disposing the SDK. |

**Example**

```javascript
try {
  await sdk.dispose();
} catch (error) {
  switch (error.name) {
    case "CafSdkDisposeError":
      console.error("SDK dispose error:", error.message);
      break;
    default:
      console.error("Unexpected dispose error:", error.name, error.message);
  }
}
```

[Go back to the top](#cyrigz6p85t0)

## isSupported <a href="#zwx6320kaxha" id="zwx6320kaxha"></a>

The `isSupported` method checks if the browser supports the SDK.

**Example**

```javascript
const isSupported: boolean = sdk.isSupported();
```

[Go back to the top](#cyrigz6p85t0)

## getIsInitialized <a href="#g928mzquhg70" id="g928mzquhg70"></a>

The `getIsInitialized` method checks if the SDK is initialized.

**Example**

```javascript
const isInitialized: boolean = sdk.getIsInitialized();
```

[Go back to the top](#cyrigz6p85t0)

## loadAiModel <a href="#mbpywqujzmy8" id="mbpywqujzmy8"></a>

{% hint style="warning" %}
If the option `enableFramingAnalyzer` was manually set to `false`, this method will have no effect when called.
{% endhint %}

The `loadAiModel` method is optional, but it can greatly enhance the SDK's loading performance. For optimal results, we recommend invoking it as early as possible in your workflow, ideally before reaching the SDK's loading screen. However, if this is not feasible or does not align with the specific requirements of your integration, the `initialize` method will automatically handle all necessary initialization tasks to ensure the SDK operates correctly.

**Handling load AI model errors**

| Error Name          | Description                                   |
| ------------------- | --------------------------------------------- |
| CafLoadAIModelError | An error occurred while loading the AI model. |

**Example**

```javascript
try {
  await documentDetector.loadAiModel();
} catch (error) {
  switch (error.name) {
    case "CafLoadAIModelError":
      console.error("SDK load AI model error:", error.message);
      break;
    default:
      console.error("Unexpected load AI model error:", error.name, error.message);
  }
}
```

[Go back to the top](#cyrigz6p85t0)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.caf.io/caf-sdk/web-javascript/getting-started/document-detector/methods.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
