---
description: >-
  Learn how to integrate the Streampixel iframe into your frontend, manage
  keyboard and mouse inputs, and ensure smooth interaction.
---

# Frontend and Application Communication

## **Overview**

Streampixel enables seamless two-way communication between your custom frontend, the iframe, and the Unreal Engine application running inside it. Using JavaScript methods like `postMessage` and `addEventListener`, you can:

1. **Receive Messages**:
   * Listen for updates from the Unreal Engine application or iframe (e.g., stream states, custom events).
2. **Send Commands**:
   * Send commands to the Unreal Engine application or iframe for controlling audio, resolution, session state, or custom features.

This messaging framework is essential for integrating custom UIs, managing stream controls, and building tailored interactions.

***

## **Listening for Messages**

To capture messages sent from the iframe or Unreal Engine application, use the `window.addEventListener` method.

**Example: Listening for Messages**

```javascript
window.addEventListener('message', (event) => {
    // Validate the message source for security
    if (event.origin === 'https://share.streampixel.io') {
        console.log('Message received:', event.data);

        // Example: Handle stream-state updates
        if (event.data.type === 'stream-state') {
            console.log('Stream state:', event.data.value); // e.g., 'loadingComplete'
        }
    }
});
```

***

## **Sending Messages**

To interact with the iframe or Unreal Engine application, send messages using the `postMessage` method. This allows you to control the stream or trigger specific Unreal Engine events.

**Example: Sending Commands**

```javascript
const sendMessageToIframe = (message) => {
    const iframe = document.getElementById('streamPixelPlayer');
    if (iframe) {
        iframe.contentWindow.postMessage(message, 'https://share.streampixel.io');
    }
};

// Example: Send the muteAudio command
sendMessageToIframe({ message: 'muteAudio' });
```

***

## **Security Best Practices**

1. **Validate Incoming Messages**:
   *   Always validate `event.origin` to ensure the message is coming from the StreamPixel iframe:

       ```javascript
       if (event.origin === 'https://share.streampixel.io') {
           // Safe to process the message
       }
       ```
2. **Restrict Outgoing Messages**:
   * Replace `'*'` with the exact origin (`https://share.streampixel.io`) when sending messages via `postMessage` to enhance security.
