What is Broadcast Channel API in JavaScript (Life Saver)
Let suppose you are working on a project and a feature come’s out to implement on it that , user has screen in which a list of hug data is showing in table or whatever form now the if the user want to add/create a new entity on this data set so he will click on create new and a new tab will open and a multi level form appear on screen. waittttttt…!!!
why we use a separate tab to create any entity??????
so here is why , because as i said earlier that we have a multi level form and we don’t want to loss it on any buy mistakenly hitting event like close form accidently or refresh page, i want to see the list data also and on that i want to fill form with some same fields values. so after complete the form and hit on the submit button the entity is create successfully. but does the list on previous tab will update ? if we are not using any Realtime event (firebase/socket.io)to update the data, nooooooo…!!! it will not update and user have to forcefully refresh the page which is quite bad impression. so here is the life saver…
Broadcast Channel API
a Broadcast channel api is the one with who you can communicate with other tabs on same origin like in our example.
we can create/join channel by Broadcast and then we can emit a message to our other tabs which are in same origin. it can communicate between windows, tabs, frames, or iframes.
so in our example i ll simple do
I will create a BroadcastChannel with any authenticate channel name when user click on Create New button and then
on useEffect/ComponentDidMount i simple register our event to listen the message whenever event hit in channel same origin
on last
when user click on submit button and if form submitted successfully. i will trigger the event by postMessage method , you can send any type of data in it.
so when event trigger on my previous tab it will auto fetch the get api and refresh the list.
hopefully now you understand the concept of Broadcast Channel API.
Wait there is one more thing, you can disconnect the channel with simply call a close() function. also SUBSCRIBE to my YouTube channel. Thankyou