BroadcastChannel是否在同一页面上工作?

时间:2017-11-29 01:59:10

标签: javascript

我的网页有

var bc = new BroadcastChannel('Consumer');

bc.onmessage = function(event) {
  alert("a");
}

bc.postMessage("hello");

它广播一条消息,该页面也需要收到相同的消息。

然而它并不起作用。我错过了什么吗?

2 个答案:

答案 0 :(得分:2)

您可以在页面上创建 BroadcastChannel 的两个实例。一个人可以充当消息的广播者,另一个人可以接收消息。

var broadcaster = new BroadcastChannel('Consumer');
var messageReceiver= new BroadcastChannel('Consumer');

messageReceiver.onmessage = function(event) {
  alert(event.data);
}

broadcaster.postMessage("hello");

请参阅此操作:https://jsfiddle.net/h56d3y27/

或包含在可重用的类中: (注意:所有浏览器都不支持类。请参阅:https://caniuse.com/#search=class以获得浏览器兼容性)

class AllInclusiveBroadcaster {  
    constructor(listener, channelName) {
    if (!channelName) channelName = "channel";
    this.broadcaster = new BroadcastChannel(channelName);
    this.messageReceiver = new BroadcastChannel(channelName);

    this.messageReceiver.onmessage = (event) => {
        listener(event.data);
    }
    }

  postmessage(data) {
    this.broadcaster.postMessage(data);
  }
}


var broadcaster = new AllInclusiveBroadcaster((data) => alert(data));

broadcaster.postmessage("Hello BroadcastChannel");

在行动中JSFiddle

也可以看到这一点

答案 1 :(得分:1)

您可以使用相同的data将一个事件(称之为您喜欢的事件)发送到文档,然后使用相同的fakeBroadcastMessage ...然后有一个侦听BroadcastChannel消息的处理程序以及您在上面创建的事件名称

在下面,代码创建并侦听var bc = new BroadcastChannel('Consumer'); function handleBroadcastMessage(event) { // do things here } bc.addEventHandler('message', handleBroadcastMessage); document.addEventListener('fakeBroadcastMessage', handleBroadcastMessage); function sendMessage(data) { bc.postMessage(data); var ev = new Event('fakeBroadcastMessage'); ev.data = data; document.dispatchEvent(ev); } sendMessage('hello');

创建了一个函数来发送bc消息和" local"消息

 final AlertDialog.Builder builder;
 AlertDialog alert;
 final ListView lvUser = new ListView(this);
 userList = tmDB.getAllUsers();
 builder = new AlertDialog.Builder(this);
 builder.setTitle(R.string.selectUser);
 ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, userList);
 lvUser.setAdapter(arrayAdapter);
 //when user selects item
 lvUser.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String name = userList.get(position);
        int userID;
        userID = tmDB.getUserId(name);
        txtName.setText(name);
    // This!!
    if(alert != null){
        alert.dismiss();
    }
    }
 });
 builder.setView(lvUser);
 alert = builder.create
 alert.show();