diff --git a/src/transports/PostMessageIframeTransport.ts b/src/transports/PostMessageIframeTransport.ts index 8b3f91d..b051c1b 100644 --- a/src/transports/PostMessageIframeTransport.ts +++ b/src/transports/PostMessageIframeTransport.ts @@ -5,10 +5,12 @@ class PostMessageIframeTransport extends Transport { public uri: string; public frame: undefined | null | Window; public postMessageID: string; + public origin: string; - constructor(uri: string) { + constructor(uri: string, origin?: string) { super(); this.uri = uri; + this.origin = origin || new URL(uri).origin; this.postMessageID = `post-message-transport-${Math.random()}`; } public createWindow(uri: string): Promise { @@ -28,7 +30,8 @@ class PostMessageIframeTransport extends Transport { }); } private messageHandler = (ev: MessageEvent) => { - this.transportRequestManager.resolveResponse(JSON.stringify(ev.data)); + if (ev.origin === this.origin) + this.transportRequestManager.resolveResponse(JSON.stringify(ev.data)); } public connect(): Promise { const urlRegex = /^(http|https):\/\/.*$/; @@ -46,7 +49,7 @@ class PostMessageIframeTransport extends Transport { const prom = this.transportRequestManager.addRequest(data, null); const notifications = getNotifications(data); if (this.frame) { - this.frame.postMessage((data as IJSONRPCData).request, "*"); + this.frame.postMessage((data as IJSONRPCData).request, this.origin); this.transportRequestManager.settlePendingRequest(notifications); } return prom; diff --git a/src/transports/PostMessageWindowTransport.ts b/src/transports/PostMessageWindowTransport.ts index 1ad2fbb..2f53e40 100644 --- a/src/transports/PostMessageWindowTransport.ts +++ b/src/transports/PostMessageWindowTransport.ts @@ -18,10 +18,12 @@ class PostMessageTransport extends Transport { public uri: string; public frame: undefined | null | Window; public postMessageID: string; + public origin: string; - constructor(uri: string) { + constructor(uri: string, origin?: string) { super(); this.uri = uri; + this.origin = origin || new URL(uri).origin; this.postMessageID = `post-message-transport-${Math.random()}`; } @@ -36,7 +38,8 @@ class PostMessageTransport extends Transport { } private messageHandler = (ev: MessageEvent) => { - this.transportRequestManager.resolveResponse(JSON.stringify(ev.data)); + if (ev.origin === this.origin) + this.transportRequestManager.resolveResponse(JSON.stringify(ev.data)); } public connect(): Promise { @@ -55,7 +58,7 @@ class PostMessageTransport extends Transport { const prom = this.transportRequestManager.addRequest(data, null); const notifications = getNotifications(data); if (this.frame) { - this.frame.postMessage((data as IJSONRPCData).request, this.uri); + this.frame.postMessage((data as IJSONRPCData).request, this.origin); this.transportRequestManager.settlePendingRequest(notifications); } return prom;