Urooj
Urooj

Reputation: 354

How to identify if the current tab is the source of message in Broadcast Channel API?

I want to use Broadcast Channel API in my Angular application to maintain logged in state across tabs. But the tab from which the user is logging in needs to run a little different code than the other tabs. I am setting the handler for MessageEvent on application load. As a result, the tab generating the login message is also executing this handler, which it will because message is dispatched to all listeners. But in the listener, I want to be able to identify if the current tab was the source of message, in that case do nothing. Is there any simple way?

Upvotes: 3

Views: 748

Answers (1)

Daniele Giuliani
Daniele Giuliani

Reputation: 1

As is stated in the MDN docs the broadcast Channel API, it returns a MessageEvent that inherits from Event.

Message event object has a read-only property source that can be compared against self property, given that you can do a simple condition as follows:

if(event.source !== self)

You should be able to separate the logic for a sender and receiver.

Upvotes: 0

Related Questions