# usePostMessageSender

*Category:* Utilities
*Section:* Browser & device hooks
*Source:* https://uikit.developers.rio.cloud/#/utilities/usePostMessageSender
*Captured:* 2026-04-27T14:59:41.816Z

Helper hook to fire postMessage events to other windows: a specific target (including yourself), the parent or top window, or every iframe on the page. It uses the wildcard target origin (*) and no-ops when a target window is missing, so it is safe to call even when an iframe or parent is not present.

## usePostMessageSender

### Example: Example 1

Use the buttons below to dispatch messages using usePostMessageSender . The gray box below is a real &lt;iframe&gt; that listens for your messages and sends an IFRAME_ECHO back.
Send to Self (Window) Send to Iframe (Ref) Broadcast to All Iframes Send to Parent
Target Iframe
This iframe acts as a separate window context. It runs a script to display what it receives.

Activity Log
Shows outgoing confirmations and incoming "Echos" from the iframe.

#### React (tsx)

```tsx
import { useEffect, useRef, useState } from 'react';

import ButtonToolbar from '@rio-cloud/rio-uikit/ButtonToolbar';
import Button from '@rio-cloud/rio-uikit/components/button/Button';
import usePostMessageSender from '@rio-cloud/rio-uikit/usePostMessageSender';
import useIncomingPostMessages from '@rio-cloud/rio-uikit/useIncomingPostMessages';

export default () => {
    const { sendMessage, sendMessageToAllIframes, sendMessageToParent } = usePostMessageSender();

    const [logs, setLogs] = useState<string[]>([]);

    // We use a ref to target a specific iframe for the "Single Target" test
    const iframeRef = useRef<HTMLIFrameElement>(null);

    // 1. LISTEN FOR REPLIES (ECHOS)
    // We reuse the receiving hook to verify that our sent messages were actually processed
    // by the target (the iframe or window) and replied to.
    useIncomingPostMessages({
        handlers: {
            // The iframe in this demo is programmed to send this event back
            IFRAME_ECHO: (payload: { type: string; payload: unknown }) => {
                addLog(`Received ECHO from iframe: ${JSON.stringify(payload)}`);
            },
        },
    });

    // Also listen for raw messages to catch self-sent messages
    useIncomingPostMessages(event => {
        if (event.data === 'Hello Self!') {
            addLog('Received self-sent message: "Hello Self!"');
        }
    });

    const addLog = (msg: string) => setLogs(prev => [...prev, `[${new Date().toLocaleTimeString()}] ${msg}`]);

    // 2. SENDING ACTIONS
    const handleSendToSelf = () => {
        // Sending to 'window' is useful for decoupling components on the same page
        sendMessage('Hello Self!', window);
        addLog('Sent "Hello Self!" to current window');
    };

    const handleSendToIframe = () => {
        if (iframeRef.current?.contentWindow) {
            // Target a specific window (the iframe)
            const payload = { id: 123, text: 'Direct message' };
            sendMessage({ type: 'UPDATE_DATA', payload }, iframeRef.current.contentWindow);
            addLog('Sent UPDATE_DATA to specific iframe');
        }
    };

    const handleBroadcast = () => {
        // Useful if you have multiple widgets/iframes and want to notify all of them
        sendMessageToAllIframes({ type: 'GLOBAL_RESET' });
        addLog('Broadcasted GLOBAL_RESET to all iframes');
    };

    const handleSendToParent = () => {
        // This might not do much if you are top-level, but won't crash
        sendMessageToParent('Hello Parent!');
        addLog('Sent message to parent window (check console if inside iframe)');
    };

    return (
        <>
            <p className='margin-bottom-20'>
                Use the buttons below to dispatch messages using <code>usePostMessageSender</code>. The gray box below
                is a real <code>&lt;iframe&gt;</code> that listens for your messages and sends an <b>IFRAME_ECHO</b>{' '}
                back.
            </p>

            <ButtonToolbar>
                <Button onClick={handleSendToSelf}>Send to Self (Window)</Button>
                <Button onClick={handleSendToIframe}>Send to Iframe (Ref)</Button>
                <Button onClick={handleBroadcast}>Broadcast to All Iframes</Button>
                <Button onClick={handleSendToParent}>Send to Parent</Button>
            </ButtonToolbar>

            <div className='display-grid grid-cols-1 grid-cols-2-md margin-y-20 gap-25'>
                <div>
                    <h5>Target Iframe</h5>
                    <p className='text-color-darker margin-y-10'>
                        This iframe acts as a separate window context. It runs a script to display what it receives.
                    </p>
                    <iframe
                        ref={iframeRef}
                        title='Receiver demo'
                        className='width-100pct height-200 border rounded'
                        srcDoc={iframeScript} // See variable at bottom of file
                    />
                </div>

                <div>
                    <h5>Activity Log</h5>
                    <p className='text-color-darker margin-y-10'>
                        Shows outgoing confirmations and incoming "Echos" from the iframe.
                    </p>
                    <EventTextarea events={logs} />
                </div>
            </div>
        </>
    );
};

const EventTextarea = ({ events }: { events: string[] }) => {
    const textareaRef = useRef<HTMLTextAreaElement>(null);

    useEffect(() => {
        if (textareaRef.current) {
            textareaRef.current.scrollTop = textareaRef.current.scrollHeight;
        }
    }, [events]);

    return (
        <textarea
            ref={textareaRef}
            readOnly
            spellCheck={false}
            value={events.join('\n')}
            className='form-control width-100pct height-200 padding-15 font-size-12'
        />
    );
};

// This HTML/JS blob is injected into the iframe to simulate a receiving widget
const iframeScript = `
<!DOCTYPE html>
<html>
<body style="background-color: #f9f9f9; font-family: sans-serif; padding: 10px; margin: 0;">
    <h4 style="margin-top: 0; color: #555;">Iframe Content</h4>
    <div id="display" style="font-size: 13px; color: #333;">Waiting for messages...</div>
    <script>
        window.addEventListener('message', (event) => {
            // Ignore react-devtools
            if(typeof event.data === 'object' && event.data?.source?.startsWith('react-devtools')) return;

            const display = document.getElementById('display');
            const dataStr = typeof event.data === 'string' ? event.data : JSON.stringify(event.data);
            
            display.innerHTML = '<strong>Received:</strong><br/>' + dataStr;
            display.style.backgroundColor = '#e6fffa';
            setTimeout(() => display.style.backgroundColor = 'transparent', 500);

            // Send an ECHO back to the parent to prove communication loop
            if (event.data && typeof event.data === 'object') {
                window.parent.postMessage({
                    type: 'IFRAME_ECHO',
                    payload: event.data
                }, '*');
            }
        });
    </script>
</body>
</html>
`;
```

#### HTML (html)

```html
<p class="margin-bottom-20">Use the buttons below to dispatch messages using <code>usePostMessageSender</code>. The gray box below is a real <code>&lt;iframe&gt;</code> that listens for your messages and sends an <b>IFRAME_ECHO</b> back.</p>
<div class="btn-toolbar">
    <button type="button" class="btn btn-default btn-component" tabindex="0">Send to Self (Window)</button>
    <button type="button" class="btn btn-default btn-component" tabindex="0">Send to Iframe (Ref)</button>
    <button type="button" class="btn btn-default btn-component" tabindex="0">Broadcast to All Iframes</button>
    <button type="button" class="btn btn-default btn-component" tabindex="0">Send to Parent</button>
</div>
<div class="display-grid grid-cols-1 grid-cols-2-md margin-y-20 gap-25">
    <div>
        <h5>Target Iframe</h5>
        <p class="text-color-darker margin-y-10">This iframe acts as a separate window context. It runs a script to display what it receives.</p>
        <iframe title="Receiver demo" class="width-100pct height-200 border rounded" srcdoc="
&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;body style=&quot;background-color: #f9f9f9; font-family: sans-serif; padding: 10px; margin: 0;&quot;&gt;
    &lt;h4 style=&quot;margin-top: 0; color: #555;&quot;&gt;Iframe Content&lt;/h4&gt;
    &lt;div id=&quot;display&quot; style=&quot;font-size: 13px; color: #333;&quot;&gt;Waiting for messages...&lt;/div&gt;
    &lt;script&gt;
        window.addEventListener('message', (event) =&gt; {
            // Ignore react-devtools
            if(typeof event.data === 'object' &amp;&amp; event.data?.source?.startsWith('react-devtools')) return;

            const display = document.getElementById('display');
            const dataStr = typeof event.data === 'string' ? event.data : JSON.stringify(event.data);
            
            display.innerHTML = '&lt;strong&gt;Received:&lt;/strong&gt;&lt;br/&gt;' + dataStr;
            display.style.backgroundColor = '#e6fffa';
            setTimeout(() =&gt; display.style.backgroundColor = 'transparent', 500);

            // Send an ECHO back to the parent to prove communication loop
            if (event.data &amp;&amp; typeof event.data === 'object') {
                window.parent.postMessage({
                    type: 'IFRAME_ECHO',
                    payload: event.data
                }, '*');
            }
        });
    &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
">
        </iframe>
    </div>
    <div>
        <h5>Activity Log</h5>
        <p class="text-color-darker margin-y-10">Shows outgoing confirmations and incoming "Echos" from the iframe.</p>
        <textarea readonly="" spellcheck="false" class="form-control width-100pct height-200 padding-15 font-size-12">
</textarea>
    </div>
</div>
```

#### Props: Returns

### Returns

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| sendMessage | (message: unknown, targetWindow: WindowProxy \| null \| undefined) => void | — | Send a message to the provided window (or to yourself if you pass window). Does nothing if target is null/undefined. |
| sendMessageToParent | (message: unknown) => void | — | Send a message to the parent window (no-op when already top-level). |
| sendMessageToTop | (message: unknown) => void | — | Send a message to the top window (no-op when already top-level). |
| sendMessageToAllIframes | (message: unknown) => void | — | Broadcast a message to every iframe found on the page. |