Skip to content

Commit

Permalink
Relay postMessage events with { type: "relay" } from WordPress onto t…
Browse files Browse the repository at this point in the history
…he outside app
  • Loading branch information
adamziel committed Apr 26, 2023
1 parent 0962f89 commit f66b172
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions packages/playground/remote/src/lib/boot-playground-remote.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,7 @@ export async function bootPlaygroundRemote() {
serviceWorkerUrl + '',
serviceWorkerVersion
);
setupPostMessageRelay(wpFrame, getOrigin(await playground.absoluteUrl));
wpFrame.src = await playground.pathToInternalUrl('/');

setAPIReady();
Expand All @@ -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<T>(value: string | undefined | null, latest: T) {
if (!value || value === 'latest') {
return (latest as string).replace('.', '_');
Expand Down

0 comments on commit f66b172

Please sign in to comment.