Есть два варианта:
parent, top, iframe.contentWindow).window.postMessage + обработка события message.Минимальные примеры:
// Родитель → iframe (разные origin)
iframeEl.contentWindow.postMessage({ type: 'PING' }, 'https://child.example');// iframe → родитель
window.addEventListener('message', (e) => {
if (e.origin !== 'https://parent.example') return;
if (e.data?.type === 'PING') e.source?.postMessage({ type: 'PONG' }, e.origin);
});// Один и тот же origin: из iframe
parent.doSomething?.();— Всегда проверяйте event.origin и ставьте точный targetOrigin (не *).
Один и тот же origin:
parent/top.iframeEl.contentWindow.Разные origin:
postMessage и событие message.targetOrigin и валидируем event.origin.// Родитель → iframe
iframeEl.addEventListener('load', () => {
iframeEl.contentWindow.postMessage({ type: 'INIT' }, 'https://child.example');
});// iframe: приём
window.addEventListener('message', (e) => {
if (e.origin !== 'https://parent.example') return;
if (e.data?.type === 'INIT') e.source?.postMessage({ ok: true }, e.origin);
});event.origin, тип и схему данных.targetOrigin: "*", указывайте точный origin.type, payload, requestId.<!-- Ограничения iframe -->
<iframe src="https://child.example"
sandbox="allow-scripts allow-same-origin"
referrerpolicy="no-referrer"></iframe>Для двунаправленного канала с портами:
const { port1, port2 } = new MessageChannel();
iframeEl.contentWindow.postMessage({ type: 'CHANNEL' }, 'https://child.example', [port2]);
port1.onmessage = (e) => { /* обработка */ };load iframe.origin или используется *.postMessage).postMessage + строгая проверка origin и протокола.window.parent/window.frames:// Прямой доступ
parent.doSomething?.(); // из iframe
iframeEl.contentWindow.doTask?.(); // из родителяlocalStorage + storage:// Отправка
localStorage.setItem('command', 'REFRESH');
// Приём в другом окне/iframe того же origin
window.addEventListener('storage', (e) => { if (e.key === 'command') {/* ... */} });BroadcastChannel:const channel = new BroadcastChannel('ui-sync');
channel.onmessage = (e) => {/* ... */};
channel.postMessage({ type: 'READY' });BroadcastChannel или localStorage+storage.postMessage.event.origin, валидируйте type/payload.targetOrigin (не *).sandbox и права.