# UCP CRM Iframe Communication

Source: https://docs.qvoice.net/docs/ucp-crm-iframe-communication/

## Overview

This document describes the communication protocol between UCP and embedded CRM iframes using the `postMessage` API. This allows CRM applications loaded within UCP tabs to send commands back to the parent UCP application.

---

## How It Works

UCP renders CRM pages inside iframes within the CRM tabs section. These iframes can communicate with UCP by sending messages using the browser's `postMessage` API. UCP listens for these messages and performs the corresponding actions.

---

## Sending Messages from the Iframe

From within the CRM iframe, use the following pattern to send messages to UCP:

```
window.parent.postMessage({
  type: 'EVENT_TYPE',
  payload: { /* optional data */ }
}, '*')
```

### Parameters

- **type** (string, required): The event type identifier. UCP uses this to determine which action to perform.
- **payload** (object, optional): Additional data required for the event.

---

## Supported Events

### Event: `CLOSE_CRM_TAB`

Closes the CRM tab that sent the message. UCP automatically identifies the source iframe and closes the corresponding tab.

#### Fields

- **type** (string): Must be `"CLOSE_CRM_TAB"`.

#### Example

```
window.parent.postMessage({
  type: 'CLOSE_CRM_TAB'
}, '*')
```

---

## Security Considerations

- Messages are accepted from any origin (`'*'`). Ensure your CRM application validates the parent context if needed.
- UCP validates message structure before processing (requires `type` field).

---

## Message Flow Overview

```
┌─────────────────┐                    ┌─────────────────┐
│   CRM Iframe    │                    │       UCP       │
└────────┬────────┘                    └────────┬────────┘
         │                                      │
         │  postMessage({ type: 'CLOSE_CRM_TAB' })
         │─────────────────────────────────────>│
         │                                      │
         │                          Identify iframe source
         │                          Find matching tab
         │                          Close tab
         │                                      │
         │              Tab closed              │
         │<─────────────────────────────────────│
         │                                      │
```
