Sharing Websocket connection between multiple tabs?

672 views Asked by At

I'm having difficulty figuring out the best method of sharing a WebSocket connection between multiple tabs. It seems like BroadcastEvent and SharedWorker are two modern APIs that can be used for this task. BroadcastEvent and SharedWorker seem like the solve the same problem, but I've seen solutions that use both together, something like this:

// worker.js

const socket = new WebSocket('url')
const broadcastChannel = new BroadcastChannel('example-broadcast')

socket.onmessage = ({ data }) => {
  broadcastChannel.postMessage(data)
}
// connection.js

const sharedWorker = new SharedWorker(new URL('worker.js', import.meta.url), {
  type: 'module',
  name: 'example-worker',
})
sharedWorker.port.start()
sharedWorker.port.onmessage = ({ data }) => {
  switch (data.type) {
    case 'message':
      console.log(data)
      break
  }
}

const broadcastChannel = new BroadcastChannel('example-broadcast')
broadcastChannel.addEventListener('message', ({ data }) => {
  switch (data.type) {
    case 'message':
      console.log(data)
      break 
  }
})

Is this a reasonable approach? Is it necessary to have both BroadcastChannel and SharedWorker here or can it be accomplished in a simpler manner? It's difficult to find answers about this situation that aren't from 2012 and use localhost and other outdated solutions.

0

There are 0 answers