BroadcastChannel testing in chrome developer tools console isn't working

2.9k views Asked by At

I am testing the BroadcastChannel functionality and I'am having trouble. I open two Chrome windows and the dev tools for each. On the console I write:

const z = new BroadcastChannel('blarg')
z.onmessage = function (ev) {console.log(ev)}

I can examine z and it has the function saved to the onmessage prop so it all looks good. However, when I test:

z.postMessage('sweet')

in one of the consoles, nothing shows in the other. I would expect since both Chrome windows are subscribed to the broadcast channel blarg and have a function to console log the message that is posted, I would see the message sweet to be shown in the other console but nothing happens.

So two questions:

Can't I test BroadcastChannel interface in the devtools console like this?

If so, what am I missing about how BroadcastChannel works?

1

There are 1 answers

0
Paolo On

It works if:

  1. the communication happens on the same origin
  2. the channel name is the same on both ends (blarg in your case, but it could also be "")
  3. you don't expect to receive the message if you are the sender

When you say

I open two chrome windows and the dev tools for each.

call them A and B. In nomenclature A and B are defined as "browsing contexts", and they could also be tabs, frames or iframes.

The following code is an example that satisfies conditions 1. and 2.

devtools A:

location.href = 'https://example.com'
z = new BroadcastChannel('blarg')
z.onmessage = (ev) => { console.log(ev) }

devtools B:

location.href = 'https://example.com'
z = new BroadcastChannel('blarg')
z.onmessage = (ev) => { console.log(ev) }

Condition 1 is also satisfied when browser contexts (windows, tabs, frames or iframes) don't "point" to any regular url (for example when you press CTRL+T to open a new tab). In this case the origin has the special value of chrome://new-tab-page.

Said that, if you post from A to B, B will receive the message and console.log it. The same applies vice versa.