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/[email protected]"></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')keyis 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 anEventEmitterinstance.
Emits an event to its own browser tab, as well as to other browser tabs of the same-origin.
eventNameis a string.emitter.onwill watch for this string.- You can have any number of
args. They must be JSON serializable.
Watches for events on other browser tabs of the same-origin, as well as its own browser tab.
eventNameis 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....argsare the arguments passed toemitter.emit(eventName, ...args). TheeventNameis 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