Skip to content

Commit

Permalink
Rewrite messaging to ensure message order is correct (#132)
Browse files Browse the repository at this point in the history
  • Loading branch information
darkwing authored Feb 10, 2022
1 parent 438bc2d commit 3ae4ae8
Showing 1 changed file with 15 additions and 4 deletions.
19 changes: 15 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ class LedgerBridgeKeyring extends EventEmitter {

this.iframeLoaded = false
this._setupIframe()

this.currentMessageId = 0
this.messageCallbacks = {}
}

serialize () {
Expand Down Expand Up @@ -455,6 +458,8 @@ class LedgerBridgeKeyring extends EventEmitter {
delete this.delayedPromise
}
}

this._setupListener()
}
document.head.appendChild(this.iframe)
}
Expand All @@ -467,18 +472,24 @@ class LedgerBridgeKeyring extends EventEmitter {

_sendMessage (msg, cb) {
msg.target = 'LEDGER-IFRAME'

this.currentMessageId += 1
msg.messageId = this.currentMessageId

this.messageCallbacks[this.currentMessageId] = cb
this.iframe.contentWindow.postMessage(msg, '*')
}

_setupListener () {
const eventListener = ({ origin, data }) => {
if (origin !== this._getOrigin()) {
return false
}

if (data && data.action && data.action === `${msg.action}-reply` && cb) {
cb(data)
return undefined
if (data && this.messageCallbacks[data.messageId]) {
this.messageCallbacks[data.messageId](data)
}

window.removeEventListener('message', eventListener)
return undefined
}
window.addEventListener('message', eventListener)
Expand Down

0 comments on commit 3ae4ae8

Please sign in to comment.