## Adding an Avatar iFrame to a Web Page
Trulience avatars can be embedded in a web page using an <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/iframe" target="_blank">iFrame</a>:
```html
<iframe 
    height="600px"
    src="https://www.trulience.com/avatar/<your-avatar-id>"
    allow="camera; microphone; fullscreen; accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
    frameborder="0" 
    allowfullscreen>
</iframe>
```

Here's how this embed code looks in action:

<iframe style="margin-bottom: 20px" height="600px" width="100%" allow="camera; microphone; fullscreen; accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" src="https://www.trulience.com/avatar/6038809566353378449?dialPageBackground=white&overlayButtonColor=#ff6200" frameborder="0" allowfullscreen></iframe>

### Authentication

By default, newly created avatars are public. To restrict access to your avatar, you can make it private and require a JWT token for authentication.

To set up private avatars:
1. Make your avatar private in the dashboard (Avatar Creator → Edit → ADVANCED tab → Privacy dropdown)
2. Create an API key with the "Generate Tokens" permission
3. Generate tokens from your backend using the `/auth/generate-token` endpoint

See the [Security documentation](/docs/trulience-platform/security) for full setup instructions.

Once you have a token, append it to the iFrame's `src` attribute:

```html
<iframe src="https://www.trulience.com/avatar/<your-avatar-id>?token=<your-token>"></iframe>
```

If your avatar is public, you can omit the token from the URL.

## Configuring the UI

You will notice that the avatar embed comes with some inbuilt UI. You can configure this UI by appending query parameters to the avatar URL or by editing your avatars' client JSON configuration via the dashboard. 

### Configuration Parameters
The following parameters can be used to configure the behaviour of the iframe:

| Parameter             | Description                                                                                       |
|-----------------------|---------------------------------------------------------------------------------------------------|
| `connect`               | If set to true, the client will connect automatically when visiting the avatar link - bypassing the 'dial' screen   |
| `micOff`                | If set to true, the microphone will be muted by default                                           |
| `speakerOff`            | If set to true, the speaker will be muted by default                                              |
| `hideFS`                | If set to true, hides the full screen button                                                      |
| `hideChatInput`         | If set to true, hides the chat input box                                                          |
| `hideChatHistory`       | If set to true, hides the chat history                                                            |
| `hideLetsChatBtn`       | If set to true, hides the dial button                                                             |
| `hideMicButton`         | If set to true, hides the microphone button preventing the users from being able to mute/unmute   |
| `hideHangUpButton`      | If set to true, hides the hang up button                                                          |
| `hideSpeakerButton`     | If set to true, hides the speaker button                                                          |
| `dialButtonText`        | Text that appears on the dial button                                                              |
| `msgOnConnect`          | Message (string) sent to the avatar on connection                                                 |
| `screenAspectRatio`     | Sets the aspect ratio of the visible video area e.g. 16:9, 4:3, 1:1 etc.                          |
| `chatInputBoxWidth`     | Can be set to the width of the visible video area above, using window                             |
| `showLogo`              | If set to true, the client will show either the default Trulience logo or the provided logoSrc    |
| `logoPosition`          | Can be right or left                                                                              |
| `logoSrc`               | The https location of the logo image to be displayed in top right or left of visible video window |
| `registerTrlEvents`     | List of events that should be notified to iframe's parent as and when they occur                  |
| `fullscreen`            | If set to true, the avatar will be displayed in fullscreen mode                                   |
| `disableDragging`       | If set to true, dragging to resize the avatar will be disabled                                    |
| `token`                 | Provide a JWT token to authenticate access to private avatars. See [Security](/docs/trulience-platform/security) for setup. |
| `controlButtonPosition` | Can be center, right or left                                                                      |
| `hideToast`             | If set to true, the client will not display toast alerts                                          |


### Adjusting Colour

Here's a list of colour attributes you can adjust using CSS colour strings, e.g. `#ffffff` or `pink`:

- `dialPageBackground`
- `dialButtonTextColor`
- `dialButtonBackground`
- `chatScreenBGColor`
- `userChatBubbleBGColor`
- `avatarChatBubbleBGColor`
- `userChatBubbleBorderColor`
- `avatarChatBubbleBorderColor`
- `userChatBubbleTextColor`
- `avatarChatBubbleTextColor`
- `inputBoxBGColor`
- `inputBoxBorderColor`
- `inputBoxTextColor`
- `sendButtonBGColor`
- `sendButtonArrowColor`
- `sendButtonBorderColor`
- `borderColorBetweenInputAndScreen`
- `overlayButtonColor`
- `loadingBarColor`

#### Example

Here's an example, demonstrating styling using query params:
```html
<iframe 
    height="700px" 
    allow="camera; microphone; fullscreen" 
    src="https://www.trulience.com/avatar/<id>?chatScreenBGColor=#e7e7e7&userChatBubbleBGColor=#ff6200&avatarChatBubbleBGColor=#000000&userChatBubbleBorderColor=none&avatarChatBubbleBorderColor=none&userChatBubbleTextColor=white&avatarChatBubbleTextColor=white&inputBoxBGColor=#fff&inputBoxBorderColor=#fff&inputBoxTextColor=inherit&sendButtonBGColor=white&sendButtonArrowColor=#000000&sendButtonBorderColor=none&borderColorBetweenInputAndScreen=#f0f0f0" 
    frameborder="0"
    allow="camera; microphone; fullscreen; accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
    allowfullscreen>
</iframe>
```

## iFrame messaging
Behind the scenes, the iFrame embed is loading the [Trulience SDK](/docs/developer/javascript). You can interact with the SDK through iFrame messaging.

### Listening to SDK Events

You can register which [SDK events](/docs/developer/javascript#available-events) you want to listen to by appending them to your iFrame's `src` attribute via a query param, for example:

```html
<iframe src="https://www.trulience.com/avatar/<id>?registerTrlEvents=auth-success,auth-fail,mic-update,speech-recognition-start,speech-recognition-end,speech-recognition-final-transcript" />
```

#### Extra iFrame Events

On top of the existing SDK events, the iframe also dispatches the following events:

| Event Name | Description | Params|
|------------|-------------|-------|
| `trl-chat` | Fired when a chat message is received from the server.	| `{message, agentName, sttResponse, senderType}` |
| `trl-respond-avatar-photo-url` | Fired in response to the trl-request-avatar-photo-url request from the iframe's parent. | URL pointing to the photo of the avatar. |

Please refer to our SDK documentation to find out more about events like `auth-success`.

#### Example

You can listen to iFrame events like this:

```javascript
window.addEventListener("message", (event) => {
    
    // Verify event.origin as necessary.
    if (event.origin) {
        // Test the origin here and return if it does not match the expected value.
    }

    if (event.data !== null && event.data !== undefined) {
        let eventData = event.data;
        console.log("Event name = " + eventData.name + " | Event parameters = " + eventData.params);
    }
}, false);
```

### Sending Events

The iframe listens and reacts to the following events:

| Message Name                | Description                                                                                     | Params                                                                           |
|-----------------------------|-------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------|
| `trl-request-avatar-photo-url`| Request for a link to the avatar photo that is set in the avatar config                         | N/A                                                                              |
| `trl-unregister-events`       | Send this to unregister for notifications of various events registered in the iframe Source URL.| Comma-separated list of event names to unregister, ideally matching those registered. |
| `trl-chat`                    | Send a message for Trulience to process and make the avatar speak the response                  | Text to be processed by Trulience.                                               |
| `trl-mic-status`              | Send this message to mute/unmute the mic                                                        | `true` to unmute, `false` to mute the mic.                                       |
| `trl-set-speaker-status`      | Send this message to mute/unmute the speaker                                                    | `true` to unmute, `false` to mute the speaker.                                   |
| `start-call`                  | Start the session with the avatar. Optionally pass a JWT token for private avatars.             | `token` (optional): JWT token for authentication                                 |
| `end-call`                    | Message to terminate the ongoing session with the avatar                                        | N/A                                                                              |

#### Example

You can define functions to send iFrame events like this:

```javascript
const sendChatMessage = (message) => {
    const dataToSend = { "command" : "trl-chat", "message" : message};
    const iframe = document.getElementById('iframeId');
    iframe.contentWindow.postMessage(dataToSend, "*");
}
```

Start a call with a JWT token (for private avatars):

```javascript
const iframe = document.getElementById('iframeId');
iframe.contentWindow.postMessage({ command: 'start-call', token: jwt }, '*');
```

End a call:

```javascript
const iframe = document.getElementById('iframeId');
iframe.contentWindow.postMessage({ command: 'end-call' }, '*');
```

<!-- TODO: include a full interactive example? we could show a split with code | avatar -->