Angular BroadcastChannel not working on Safari

3.3k views Asked by At

BroadcastChannel is a native function in Angular. It doesn't require importing an additional library. You just declare it like this...

const broadcastChannel = new BroadcastChannel('demo-broadcast-channel');

You send messages like this...

this.counter++;
 
broadcastChannel.postMessage({
  type: 'counter',
  counter: this.counter
  });
}

and you receive them like this...

const broadcastChannel = new BroadcastChannel('demo-broadcast-channel');
 
this.broadcastChannel.onmessage = (message) => {
  console.log('Received message', message);
}

This works on ALL browsers except Safari on all Apple devices, where we get:

ReferenceError: Can't find variable: BroadcastChannel

Any suggestions?

Thanks.

2

There are 2 answers

0
AppDreamer On

Phix is correct in his comment, it's the browser API and currently Safari doesn't support it at all. However, they shouldn't make the entire website crash because it's not handled. That's just stubborn ignorance or intent.

Here's the work-around that I didn't see in any of the standard example code. Wrap any bc var instantiation line and subsequent usage in a try/catch, and in the catch use any number of alternatives. One thread from an apple dev actually suggested using cookies, but that seems like a bad idea to me. Others suggested building your own message_broadcast. Here's a complete thread on some alternatives.

Here's the fix for this problem:

try {
  const broadcastChannel = new BroadcastChannel('demo-broadcast-channel');
  this.counter++;
 
  broadcastChannel.postMessage({
    type: 'counter',
    counter: this.counter
    });
  }
}
catch {
  //do some alternative here...
}
0
Ron Jonk On

It should be supported since safari 15.4 see https://caniuse.com/broadcastchannel