-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathiframe.ts
More file actions
165 lines (155 loc) · 5.02 KB
/
iframe.ts
File metadata and controls
165 lines (155 loc) · 5.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
import {
createTransportFromMessagePort,
type RPCMessagePortTransportOptions,
} from "../index.js";
const IFRAME_MSG_KEY = "[iframe-transport]";
const IFRAME_READY_MSG = "[iframe-transport-ready]";
async function waitForLoad(element: HTMLElement) {
const readyState = (element as HTMLIFrameElement).contentDocument?.readyState;
const location = (element as HTMLIFrameElement).contentWindow?.location.href;
return location !== "about:blank" && readyState === "complete"
? Promise.resolve()
: new Promise((resolve) => element.addEventListener("load", resolve));
}
async function portReadyPromise(port: MessagePort) {
return new Promise<void>((resolve) => {
port.addEventListener("message", function ready(event) {
if (event.data === IFRAME_READY_MSG) {
port.removeEventListener("message", ready);
resolve();
}
});
});
}
/**
* Options for the iframe transport.
*/
export type RPCIframeTransportOptions = Omit<
RPCMessagePortTransportOptions,
"transportId" | "remotePort"
> & {
/**
* An identifier for the transport. This is used to match the iframe with
* the parent window. If not set, a default value will be used when establishing
* the connection.
*/
transportId?: string | number;
/**
* The target origin of the iframe. This is used to restrict the domains
* that can communicate with the iframe. If not set, the iframe will accept
* messages from any origin. [Learn more about `targetOrigin` on MDN.](
* https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage#targetorigin)
*
* @default "*"
*/
targetOrigin?: string;
};
/**
* Creates a transport to communicate with an iframe. This is an asynchronous
* process because it requires waiting for the iframe to load and signal that
* it's ready to receive messages.
*
* The target iframe must use `createIframeParentTransport` with a matching
* `transportId` or `filter` option (if set).
*
* Uses `MessageChannel` under the hood. [Learn more about the Channel Messaging
* API on MDN.](https://developer.mozilla.org/en-US/docs/Web/API/Channel_Messaging_API/Using_channel_messaging)
*
* Using the `transportId` option is recommended to
* avoid conflicts with other connections. If security is a concern, the
* `targetOrigin` option should be set to the expected origin of the iframe.
* [Learn more about `targetOrigin` on MDN.](
* https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage#targetorigin).
*
* @example
*
* ```ts
* const rpc = createRPC<ParentSchema, IframeSchema>({
* transport: await createIframeTransport(iframeElement, {
* transportId: "my-iframe"
* }),
* // ...
* });
* ```
*
*/
export async function createIframeTransport(
/**
* The iframe element to communicate with.
*/
iframe: HTMLIFrameElement,
/**
* Options for the iframe transport.
*/
options: RPCIframeTransportOptions = {},
) {
const channel = new MessageChannel();
const { port1, port2 } = channel;
port1.start();
const transport = createTransportFromMessagePort(port1, options);
const readyPromise = portReadyPromise(port1);
await waitForLoad(iframe);
if (!iframe.contentWindow) throw new Error("Unexpected iframe state");
iframe.contentWindow.postMessage(
{ [IFRAME_MSG_KEY]: options.transportId ?? "default" },
options.targetOrigin ?? "*",
[port2],
);
await readyPromise;
return transport;
}
async function waitForInit(id: string | number) {
return new Promise<MessagePort>((resolve) => {
window.addEventListener("message", function init(event) {
const { data, ports } = event;
if (data[IFRAME_MSG_KEY] === id) {
const [port] = ports;
window.removeEventListener("message", init);
resolve(port);
}
});
});
}
/**
* Options for the iframe parent transport.
*/
export type RPCIframeParentTransportOptions = Omit<
RPCMessagePortTransportOptions,
"transportId" | "remotePort"
> & {
/**
* An identifier for the transport. This is used to match the iframe with
* the parent window. If not set, a default value will be used when establishing
* the connection.
*/
transportId?: string | number;
};
/**
* Creates a transport to communicate with the parent window from an iframe. This
* is an asynchronous process because it requires waiting for the parent window
* to connect to the iframe.
*
* The parent window must use `createIframeTransport` with a matching
* `transportId` or `filter` option (if set).
*
* Using the `transportId` option is recommended to avoid conflicts with other
* connections.
*
* @example
*
* ```ts
* const rpc = createRPC<IframeSchema, ParentSchema>({
* transport: await createIframeParentTransport({ transportId: "my-iframe" }),
* // ...
* });
* ```
*/
export async function createIframeParentTransport(
options: RPCIframeParentTransportOptions = {},
) {
const port = await waitForInit(options.transportId ?? "default");
port.start();
port.postMessage(IFRAME_READY_MSG);
return createTransportFromMessagePort(port, options);
}
// TODO: iframe transport tests.