If you want to track the count of active ports connected through a BroadcastChannel, there is no direct method available. However, you can create your own solution by implementing a system where all ports respond to pings and the responses are counted within a specific time frame. Alternatively, using LocalStorage to store and update the count of each channel could be a simpler approach.
By storing the current count in localStorage for each opened channel, you can easily retrieve this value before establishing new connections. Remember that this count will be shared across different contexts communicating through the BroadcastChannel.
const active_connections = localStorage[ channel_name ] || 0;
When connecting, simply increment this count unless it exceeds a maximum limit:
if( active_connections < max_count ) {
const channel = new BroadcastChannel( channel_name );
localStorage[ channel_name ] = active_connections + 1;
}
To ensure the count decreases when a channel is closed, you can listen for the beforeunload
event:
addEventListener( 'beforeunload', (evt) => {
localStorage[ channel_name ] --;
} );
In case you explicitly close a channel using channel.close()
, remember to update the count accordingly and disable the beforeunload listener. You may also consider periodically verifying the counts using a ping method to account for any unexpected failures like page crashes.
It's worth reevaluating the need for such tracking in your design as it might indicate a flaw. If in doubt, feel free to seek further advice or open a new question addressing your concerns.