Emit events between browser tabs! (Same-origin only.)
tab-emitter
is a client-side javascript module that allows you to send events between browser tabs/windows.
The sending/recieving web pages must have the same origin.
You can not emit events between browsers, only between the same browser.
tab-emitter
is written to work with browserify. It should work with Rollup and Webpack too.
client1.js
var TabEmitter = require('tab-emitter')
var emitter = TabEmitter()
setTimeout(() => {
let data = { x: 'world' }
emitter.emit('hello', data)
}, 5000)
emitter.on('hello', data => {
console.log(data.x) // 'world'
})
client2.js
var TabEmitter = require('tab-emitter')
var emitter = TabEmitter()
emitter.on('hello', data => {
console.log(data.x) // 'world'
})
If you just want to use this module in the browser without dealing with browserify, here's how you can:
<script src="https://bundle.run/tab-emitter@1.0.11"></script>
<script>
var emitter = window.tabEmitter()
emitter.on('event', () => {
console.log('event just happened')
})
setTimeout(() => {
emitter.emit('event')
}, 5000)
</script>
var TabEmitter = require('tab-emitter')
key
is a key to uniquely identify an emitter across tabs. If the same key is used in multiple tabs, they can communicate with each other.- Returns
emitter
, which is anEventEmitter
instance.
Emits an event to its own browser tab, as well as to other browser tabs of the same-origin.
eventName
is a string.emitter.on
will watch for this string.- You can have any number of
arg
s. They must be JSON serializable.
Watches for events on other browser tabs of the same-origin, as well as its own browser tab.
eventName
is a string of the event name to watch for.handler(...args)
is a function that will be called every time the event with the given name is emitted....args
are the arguments passed toemitter.emit(eventName, ...args)
. TheeventName
is not included.
For more extended documentation, please look at the official EventEmitter
documentation. Technically, EventEmitter
is getting polyfilled by your choice of bundler. Likely with this module. But the API should be identical.
With npm do:
npm install tab-emitter