-
Notifications
You must be signed in to change notification settings - Fork 1
/
fetchiframe.html
56 lines (47 loc) · 1.76 KB
/
fetchiframe.html
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
<!DOCTYPE html>
<html>
<head>
<title>Secure Fetch Iframe</title>
</head>
<body>
<script>
const allowedOrigin = window.location.origin;
function postResponseToParent(requestEvent, responseData, isError = false) {
window.parent.postMessage({
id: requestEvent.data.id,
response: true,
success: !isError,
data: responseData,
source: "iframe"
}, allowedOrigin);
}
async function handleFetchRequest(event, requestDetails) {
try {
const { url, options } = requestDetails;
if (!url) throw new Error("Invalid URL.");
if (options?.method && !["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"].includes(options.method.toUpperCase())) {
throw new Error("Invalid HTTP method.");
}
const response = await fetch(url, options || {});
const responseBody = await response.text();
const responseDetails = {
status: response.status,
statusText: response.statusText,
headers: [...response.headers.entries()],
body: responseBody,
};
postResponseToParent(event, responseDetails);
} catch (error) {
postResponseToParent(event, { error: error.message }, true);
}
}
window.addEventListener("message", async (event) => {
if (event.origin !== allowedOrigin) return;
const { source, id, message } = event.data;
if (source !== "origin" || !id || !message.fetchRequest) return;
await handleFetchRequest(event, message.fetchRequest);
});
window.parent.postMessage({ message: "iframe-ready", source: "iframe" }, allowedOrigin);
</script>
</body>
</html>