Skip to content

Commit

Permalink
Make Parent configurable (#15)
Browse files Browse the repository at this point in the history
  • Loading branch information
안재원 (Jaewon Ahn) authored Oct 13, 2022
1 parent eb8794d commit 2680f4b
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 9 deletions.
15 changes: 7 additions & 8 deletions src/glue/parent-window.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,25 +8,24 @@ import { getGlue, isGlueEvent } from "./index.ts";
const key = "<glue>";

export interface CreateParentWindowSocketConfig {
parent?: Window | null;
parentWindowOrigin: string;
}
export async function createParentWindowSocket(
config: CreateParentWindowSocketConfig,
): Promise<Socket> {
if (globalThis.top === globalThis.self) throw new Error("This is the top.");
if (!("parent" in globalThis) || !globalThis.parent?.postMessage) {
throw new Error("There is no parent window.");
}
const { parentWindowOrigin } = config;
const { parent = globalThis.parent, parentWindowOrigin } = config;
if (!parent?.postMessage) throw new Error("There is no parent window.");
if (parent === globalThis.self) throw new Error("Invalid parent window.");
const wait = defer<void>();
const glue = getGlue();
globalThis.addEventListener("message", (event: any) => {
if (event.source !== globalThis.parent) return;
if (event.source !== parent) return;
if (!isGlueEvent(event)) return;
const [, isHandshakeMessage, payload] = event.data;
if (isHandshakeMessage) {
if (payload === "ping") {
globalThis.parent.postMessage([key, true, "pong"], "*");
parent.postMessage([key, true, "pong"], "*");
wait.resolve();
}
} else {
Expand All @@ -41,7 +40,7 @@ export async function createParentWindowSocket(
read: glue.read,
async write(data) {
const length = data.byteLength;
const { postMessage } = globalThis.parent;
const { postMessage } = parent;
postMessage([key, false, data], parentWindowOrigin, [data.buffer]);
return length;
},
Expand Down
8 changes: 7 additions & 1 deletion src/jotai/parent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,13 @@ export const socketAtom: SocketAtom = atom(async () => {
return await Promise.any([
createAndroidSocket(),
createIosSocket(),
createParentWindowSocket({ parentWindowOrigin: "*" }),
createParentWindowSocket({
parentWindowOrigin: "*",
}),
createParentWindowSocket({
parent: globalThis.opener,
parentWindowOrigin: "*",
}),
]).catch(() => undefined);
});

Expand Down

0 comments on commit 2680f4b

Please sign in to comment.