1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-12-23 09:52:26 +01:00
metamask-extension/app/scripts/contentscript.js

38 lines
1.3 KiB
JavaScript
Raw Normal View History

2015-12-19 07:05:16 +01:00
const LocalMessageDuplexStream = require('./lib/local-message-stream.js')
const PortStream = require('./lib/port-stream.js')
2016-05-06 01:04:43 +02:00
const ObjectMultiplex = require('./lib/obj-multiplex')
2015-08-02 01:33:31 +02:00
// inject in-page script
2015-08-01 03:38:02 +02:00
var scriptTag = document.createElement('script')
scriptTag.src = chrome.extension.getURL('scripts/inpage.js')
scriptTag.onload = function() { this.parentNode.removeChild(this) }
2015-08-02 01:33:31 +02:00
var container = document.head || document.documentElement
// append as first child
container.insertBefore(scriptTag, container.children[0])
2015-08-02 01:33:31 +02:00
2015-12-19 07:05:16 +01:00
// setup communication to page and plugin
var pageStream = new LocalMessageDuplexStream({
name: 'contentscript',
target: 'inpage',
})
2016-05-06 01:04:43 +02:00
pageStream.on('error', console.error.bind(console))
2016-01-15 11:03:42 +01:00
var pluginPort = chrome.runtime.connect({name: 'contentscript'})
2015-12-19 07:05:16 +01:00
var pluginStream = new PortStream(pluginPort)
2016-05-06 01:04:43 +02:00
pluginStream.on('error', console.error.bind(console))
2016-05-06 01:04:43 +02:00
// forward communication plugin->inpage
pageStream.pipe(pluginStream).pipe(pageStream)
2016-02-10 20:46:13 +01:00
// connect contentscript->inpage reload stream
2016-05-06 01:04:43 +02:00
var mx = ObjectMultiplex()
mx.on('error', console.error.bind(console))
mx.pipe(pageStream)
var reloadStream = mx.createStream('reload')
reloadStream.on('error', console.error.bind(console))
2016-05-06 01:04:43 +02:00
// if we lose connection with the plugin, trigger tab refresh
pluginStream.on('close', function(){
reloadStream.write({ method: 'reset' })
2016-05-06 01:04:43 +02:00
})