javascriptangulartypescriptgoogle-chromebroadcast-channel

Javascript: Get BroadcastChannel Subscriber Count


How do I tell if Broadcast channel exists and its subscriber count?

We have a product link, and some chrome page tabs are subscribing to a Broadcast channel. Want to see how many are listening.

const bc = new window.BroadcastChannel('channel_name');

Resources:

https://medium.com/javascript-in-plain-english/using-javascript-and-the-broadcast-channel-api-a3134739781d

Communication between tabs or windows

Using Angular Typescript environment,maybe it has a library function


Solution

  • There is no built-in way to get the count of active ports connected through the same BroadcastChannel.

    You could set up something on your own, e.g by using some pinging method where all the ports would respond and the asker just has to count the responses in a given time, but that's a bit cumbersome, makes everything async and actually using LocalStorage just for this count seems like the easiest way.

    You can keep in the localStorage the current count of each channels you'll open.

    Before each new connection the page can just check that value, since it will shared across the contexts that can communicate through the BroadcastChannel.

    const active_connections = localStorage[ channel_name ] || 0;
    

    Then when connecting, it just has to update that value.

    if( active_connections < max_count ) {
      const channel = new BroadcastChannel( channel_name );
      localStorage[ channel_name ] = active_connections + 1;
    }
    

    And the trickiest being to decrease that count when the channel gets closed. For that you will need to hook to the beforeunload event:

    addEventListener( 'beforeunload', (evt) => {
      localStorage[ channel_name ] --;
    } );
    

    Note that if your code does call channel.close(), then you should add a line to update that count there too, and to disable the beforeunload one.

    (You could still run the pinging way too to ensure the counts are still correct, since e.g if a page crashes, beforeunload could have not fired).


    I should note I can't see why you'd need to do something like this, probably something is off in your design, you should double check it, and maybe open a new question about it)