简体   繁体   English

Angular BroadcastChannel 在 Safari 上不工作

[英]Angular BroadcastChannel not working on Safari

BroadcastChannel is a native function in Angular. It doesn't require importing an additional library. BroadcastChannel是Angular中原生的function,不需要额外导入库。 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:这适用于所有浏览器,除了 Safari 在所有 Apple 设备上,我们得到:

ReferenceError: Can't find variable: BroadcastChannel

Any suggestions?有什么建议么?

Thanks.谢谢。

Phix is correct in his comment, it's the browser API and currently Safari doesn't support it at all. Phix在他的评论中是正确的,它是浏览器 API 而目前 Safari 根本不支持它。 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.在 try/catch 中包装任何 bc var 实例化行和后续使用,并在 catch 中使用任意数量的替代方案。 One thread from an apple dev actually suggested using cookies, but that seems like a bad idea to me.来自苹果开发人员的一个线程实际上建议使用 cookies,但这对我来说似乎是个坏主意。 Others suggested building your own message_broadcast.其他人建议建立自己的 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...
}

It should be supported since safari 15.4 see https://caniuse.com/broadcastchannel safari 15.4 起应该支持见https://caniuse.com/broadcastchannel

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM