1

BroadcastChannel 是 Angular 中的一个原生函数。它不需要导入额外的库。你只是这样声明它......

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

你发这样的消息...

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

你会像这样收到它们......

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

这适用于所有 Apple 设备上除 Safari 之外的所有浏览器,我们从中获得:

ReferenceError: Can't find variable: BroadcastChannel

有什么建议么?

谢谢。

4

1 回答 1

1

Phix在他的评论中是正确的,它是浏览器 API,目前 Safari 根本不支持它。但是,他们不应该让整个网站崩溃,因为它没有得到处理。那只是顽固的无知或意图。

这是我在任何标准示例代码中都没有看到的解决方法。在 try/catch 中包装任何 bc var 实例化行和后续使用,并在 catch 中使用任意数量的替代方案。来自苹果开发人员的一个帖子实际上建议使用 cookie,但这对我来说似乎是个坏主意。其他人建议建立自己的 message_broadcast。这是一些替代品的完整主题

这是解决此问题的方法:

try {
  const broadcastChannel = new BroadcastChannel('demo-broadcast-channel');
  this.counter++;
 
  broadcastChannel.postMessage({
    type: 'counter',
    counter: this.counter
    });
  }
}
catch {
  //do some alternative here...
}
于 2020-12-04T14:18:41.897 回答