Skip to content

Commit

Permalink
fix: simplify postmessage transport
Browse files Browse the repository at this point in the history
  • Loading branch information
shanejonas committed Apr 30, 2020
1 parent 1081e57 commit bdafb5a
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 17 deletions.
2 changes: 1 addition & 1 deletion src/containers/Inspector.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@ const Inspector: React.FC<IProps> = (props) => {
if (transport) {
try {
const result = await transport.sendData({
internalID: id,
internalID: json.id,
request: json,
});
const r = { jsonrpc: "2.0", result, id };
Expand Down
29 changes: 13 additions & 16 deletions src/transports/PostMessageTransport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,28 +31,25 @@ class PostMessageTransport extends Transport {
});
const el = document.getElementById("root");
el?.parentNode?.insertBefore(this.iframe, el);
});
}

public async sendData(data: JSONRPCRequestData, timeout: number | undefined = 5000): Promise<any> {
return new Promise((resolve, reject) => {
this.iframe.contentWindow?.postMessage((data as IJSONRPCData).request, this.uri);
const handleMessage = (ev: MessageEvent) => {
window.addEventListener("message", (ev: MessageEvent) => {
if (ev.origin === window.origin) {
return;
}
window.removeEventListener("message", handleMessage);
if (ev.data.error) {
reject(new JSONRPCError(ev.data.error.message, ev.data.error.code, ev.data.error.data));
}
if (ev.data.id === (data as IJSONRPCData).request.id) {
resolve(ev.data.result);
}
};
window.addEventListener("message", handleMessage, false);
this.transportRequestManager.resolveResponse(JSON.stringify(ev.data));
});
});
}

public async sendData(data: JSONRPCRequestData, timeout: number | undefined = 5000): Promise<any> {
const prom = this.transportRequestManager.addRequest(data, undefined);
if (this.iframe) {
this.iframe?.contentWindow?.postMessage((data as IJSONRPCData).request, this.uri);
} else {
return;
}
return prom;
}

public close(): void {
const el = document.getElementById(postmessageID);
el?.remove();
Expand Down

0 comments on commit bdafb5a

Please sign in to comment.