JavaScript: Retrieve the Number of Subscribers on the BroadcastChannel

Is there a way to check if a Broadcast channel exists and see how many subscribers it has?

We have a product link, and some Chrome tabs are subscribed to a Broadcast channel. We want to determine the number of listeners.

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

Working in an Angular Typescript environment, there may be a library function available for this.

Answer №1

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.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve data from JSON using AJAX

I am working with an API that provides JSON data in the following format: [{ "Code": "001", "Name": "xyz", "Members": [{ "FullName": "User1" }] }, { "Code": "002", "Name": "asd", "Members": [{ "FullName": "User2 ...

Issue with Retrieving Value in NgxLocalStorage

I am currently exploring the Visual Studio 2017 SPA Template for Angular 2 and looking to implement it in my project. My goal is to have the HomeComponent display the name of the logged-in user, which is stored in local storage using NgxLocalStorage, afte ...

Exploring Selenium: Clicking on Auto-Complete Suggestions using Python

Attempting to interact with an auto-complete search bar on the site in order to search for results. Wanting to click on the drop-down element that appears after entering a city name to perform a full city name search and obtain results. Below is the cod ...

Start flicker issue in Vue 3 transition

I have created a carousel of divs that slide in and out of view on the screen. However, I am facing an issue where during the start of each transition, when a new div is rendered (i.e., the value of carousel_2 changes), it appears without the transition-en ...

Encountering the error "Cannot access property 'stroke' of undefined" when utilizing constructors in React and p5

Hi there, I'm having trouble with my React code and could really use some assistance. Being new to React, I'm trying to create a collision system between multiple bubbles in an array, but I keep running into this undefined error: https://i.sstat ...

What could be the reason behind the issue of my HTML draggable feature not functioning properly on touch

I've set up a draggable div with headers and p tags, but I'm encountering an issue when trying to run it on a touch screen. The div tag isn't draggable in this scenario. Can anyone suggest the best solution for making this page touch screen ...

Updating the key within an array of objects

In my array of objects, I have the following data: arrayOfObject = [{'key1': [1,2]} , {'key2': [1,2,3]} , {'key3': [1,2,4]}] I know the name of the key that I want to replace in my array : var keyString = 'key1&apos ...

Angular 9 - Button unable to be clicked under certain conditions

I have a webpage that contains a lot of information, and I would like to make it easier for the user to show/hide specific parts by clicking on buttons. Check out this stackblitz to see what I've done. Here's a brief summary of the code: <but ...

What is the process for generating a null result cursor upon publication?

Is it possible to return an empty cursor in Meteor? Meteor.publish('example', function(id) { check(id, Match.Maybe(String)) if (!this.userId) return [] }) Although I want the publication to return an empty result when the user is not lo ...

Sending an array of data using Angular in a web service

Here is my model object from model.ts name_id: string[]; public generateUrlencodedParameters(token: string, id?: number): string { let urlSearchParams = new URLSearchParams(); urlSearchParams.append('name_id', this.name_id.toS ...

Tips for retrieving an element's outerHTML, innerHTML, and text content using JavaScript

I am new to the protractor framework and I have been struggling to find a way to access, using outerHTML/InnerHTML/getText(), the child elements in order to test if an <img> element is being displayed on a view. Specifically, I am working with an ng- ...

Developing multi-layered business solutions with Angular front-end that incorporate customized localization in .Net Core Entity MVC is essential for ensuring effective business logic implementation

Help me enhance and refine this code I faced challenges trying to understand and piece together this code (coding isn't my strong suit). Sharing knowledge is important, as encouraged by platforms like StackOverflow. Please help me improve and correct ...

Experiencing issues during the execution of "ng serve"

The angular project is named "PaymentApp". When running "ng serve", numerous errors are displayed instead of the default angular template. The message "Cannot GET /" is being shown. Attached images for reference: https://i.stack.imgur.com/faysG.png http ...

Tips for maintaining the active state of an item within a component that loops through a dataset

I am working with an array of objects (specifically, posts represented as strings) and I am looking to be able to edit each one individually. However, I am encountering an issue where clicking on the edit button triggers editing for all posts at once: co ...

Is it possible to implement a single OrbitControls with two cameras in ThreeJS?

Is there a way to link the OrbitControls of two canvases on the same page? For example, if the user zooms in on one canvas, I want the other canvas to also zoom in simultaneously. How could I achieve this synchronization between multiple canvases? ...

Challenge with Typescript Interfaces

Can someone help me with understanding interfaces in typescript? I am currently facing an issue with the code. The error message says: Type 'Response' is missing the following properties from type 'myObj': userId, title, id I believe ...

Transferring information to the controller and refreshing the interface (Single-page design)

I'm stuck on a personal project and could really use some help. If anyone has any feedback, it would be greatly appreciated. Thanks in advance. In my index.php file, I have a div with the id main-container. Inside this container, there are two separa ...

Having difficulty accessing custom cells in Angular ng2-smart-table for search functionality

When rendering a "custom" field, one issue that arises is that the global search feature is no longer effective within it. This could be due to the fact that the cell initially appears as a JSON object and then only a single string is rendered from that ...

What is the correct way to interpret a JSON file using TypeScript?

Encountering Error Error TS2732: Cannot locate module '../service-account.json'. It is suggested to use the '--resolveJsonModule' flag when importing a module with a '.json' extension. import serviceAccountPlay from '../ ...

Embed Text inside an HTML Canvas

As someone who is relatively new to working with html canvas, I am having a bit of trouble when it comes to containing text within the canvas area. Specifically, I am pulling text from a textarea and displaying it on the canvas, but it seems to stay as one ...