From f66b17241f7f932f2d2d958162b284e1b3e2672d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adam=20Zieli=C5=84ski?= Date: Wed, 26 Apr 2023 15:14:20 +0200 Subject: [PATCH] Relay postMessage events with { type: "relay" } from WordPress onto the outside app --- .../remote/src/lib/boot-playground-remote.ts | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/packages/playground/remote/src/lib/boot-playground-remote.ts b/packages/playground/remote/src/lib/boot-playground-remote.ts index e2440d868d..589bbd6069 100644 --- a/packages/playground/remote/src/lib/boot-playground-remote.ts +++ b/packages/playground/remote/src/lib/boot-playground-remote.ts @@ -141,6 +141,7 @@ export async function bootPlaygroundRemote() { serviceWorkerUrl + '', serviceWorkerVersion ); + setupPostMessageRelay(wpFrame, getOrigin(await playground.absoluteUrl)); wpFrame.src = await playground.pathToInternalUrl('/'); setAPIReady(); @@ -152,6 +153,31 @@ export async function bootPlaygroundRemote() { return playground; } +function getOrigin(url: string) { + return new URL(url, 'https://example.com').origin; +} + +function setupPostMessageRelay( + wpFrame: HTMLIFrameElement, + expectedOrigin: string +) { + window.addEventListener('message', (event) => { + if (event.source !== wpFrame.contentWindow) { + return; + } + + if (event.origin !== expectedOrigin) { + return; + } + + if (typeof event.data !== 'object' || event.data.type !== 'relay') { + return; + } + + window.parent.postMessage(event.data, '*'); + }); +} + function parseVersion(value: string | undefined | null, latest: T) { if (!value || value === 'latest') { return (latest as string).replace('.', '_');