Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does BroadcastChannel work on the same page?

Tags:

javascript

My web page has

var bc = new BroadcastChannel('Consumer');

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

bc.postMessage("hello");

It broadcasts a message, and the page is also required to receive the same message.

However it doesn't work. Did I miss anything?

like image 383
Gqqnbig Avatar asked Nov 29 '17 01:11

Gqqnbig


1 Answers

You can create two instances of BroadcastChannel on your page. One can act as a broadcaster for messages, the other one for receiving messages.

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

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

broadcaster.postMessage("hello");

See this in action: https://jsfiddle.net/h56d3y27/

Or wrapped in a reusable class: (note: class is not supported by all browsers. See : https://caniuse.com/#search=class for browser compatibility)

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");

See this also in action a JSFiddle

like image 105
ThdK Avatar answered Sep 27 '22 20:09

ThdK