nifty-wallet/app/scripts/lib/local-message-stream.js

57 lines
1.8 KiB
JavaScript
Raw Normal View History

2015-12-18 22:05:16 -08:00
const Duplex = require('readable-stream').Duplex
const inherits = require('util').inherits
module.exports = LocalMessageDuplexStream
inherits(LocalMessageDuplexStream, Duplex)
2016-06-21 13:18:32 -07:00
function LocalMessageDuplexStream (opts) {
2015-12-18 22:05:16 -08:00
Duplex.call(this, {
objectMode: true,
})
// this._origin = opts.origin
this._name = opts.name
this._target = opts.target
// console.log('LocalMessageDuplexStream ('+this._name+') - initialized...')
window.addEventListener('message', this._onMessage.bind(this), false)
}
// private
2016-06-21 13:18:32 -07:00
LocalMessageDuplexStream.prototype._onMessage = function (event) {
2015-12-18 22:05:16 -08:00
var msg = event.data
2016-05-05 16:04:43 -07:00
// console.log('LocalMessageDuplexStream ('+this._name+') - heard message...', event)
2015-12-18 22:05:16 -08:00
// validate message
2016-06-21 13:18:32 -07:00
if (event.origin !== location.origin) return // console.log('LocalMessageDuplexStream ('+this._name+') - rejected - (event.origin !== location.origin) ')
if (typeof msg !== 'object') return // console.log('LocalMessageDuplexStream ('+this._name+') - rejected - (typeof msg !== "object") ')
if (msg.target !== this._name) return // console.log('LocalMessageDuplexStream ('+this._name+') - rejected - (msg.target !== this._name) ', msg.target, this._name)
if (!msg.data) return // console.log('LocalMessageDuplexStream ('+this._name+') - rejected - (!msg.data) ')
2015-12-18 22:05:16 -08:00
// console.log('LocalMessageDuplexStream ('+this._name+') - accepted', msg.data)
// forward message
2016-05-05 16:04:43 -07:00
try {
this.push(msg.data)
2016-06-21 13:18:32 -07:00
} catch (err) {
2016-05-05 16:04:43 -07:00
this.emit('error', err)
}
2015-12-18 22:05:16 -08:00
}
// stream plumbing
LocalMessageDuplexStream.prototype._read = noop
2016-06-21 13:18:32 -07:00
LocalMessageDuplexStream.prototype._write = function (data, encoding, cb) {
2015-12-18 22:05:16 -08:00
// console.log('LocalMessageDuplexStream ('+this._name+') - sending message...')
var message = {
target: this._target,
data: data,
}
window.postMessage(message, location.origin)
cb()
}
// util
2016-06-21 13:18:32 -07:00
function noop () {}