-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTokenScriptIframe.tsx
More file actions
98 lines (86 loc) · 2.68 KB
/
TokenScriptIframe.tsx
File metadata and controls
98 lines (86 loc) · 2.68 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
import { handleTlinkApiRequest } from "@/lib/handle-tlink-api"
import { useEffect, useRef } from "react"
export function TokenScriptIframe(props: {
dAppUrl: string
className?: string
style?: React.CSSProperties
}) {
const iframeRef = useRef<HTMLIFrameElement>(null)
useEffect(() => {
const handleMessage = async (event: MessageEvent) => {
// We only proxy messages that originate from the child iframe
if (event.source !== iframeRef.current?.contentWindow) {
return
}
if (event.data?.source === "TLINK_API_REQUEST") {
try {
iframeRef.current?.contentWindow?.postMessage(
{
type: "TLINK_API_RESPONSE",
source: "TLINK_API_RESPONSE",
data: {
uid: event.data.data.uid,
method: event.data.data.method,
response: await handleTlinkApiRequest(
event.data.data.method,
event.data.data.payload
)
}
},
"*"
)
} catch (e) {
console.error("TLink API request failed: ", e);
iframeRef.current?.contentWindow?.postMessage({
type: "TLINK_API_RESPONSE",
source: "TLINK_API_RESPONSE",
data: {
uid: event.data.data.uid,
method: event.data.data.method,
error: e.message
}
}, "*");
}
return;
}
if (event.data?.source === "tlink") {
const resp = await chrome.runtime.sendMessage({
type: "rpc",
data: event.data.data
})
sendResponse(event.data.data, resp)
}
function sendResponse(
messageData: MessageEvent["data"],
response: any | null
) {
const data = messageData
if (response?.error) {
data.error = response.error
} else {
data.result = response.result
}
iframeRef.current?.contentWindow?.postMessage(
{ source: "tlink-rpc-resp", data },
"*"
)
}
}
window.addEventListener("message", handleMessage)
return () => {
window.removeEventListener("message", handleMessage)
}
}, [])
return (
<iframe
src={chrome.runtime.getURL(
`/sandbox.html?url=${encodeURIComponent(props.dAppUrl)}`
)}
ref={iframeRef}
allow="clipboard-write"
sandbox="allow-same-origin allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox allow-modals"
style={{ height: "100%", ...props.style }}
className={`no-scrollbar w-full rounded-lg ${props.className}`}
/>
)
}