On this page

C

BroadcastChannel extends EventTarget

History

Instances of BroadcastChannel allow asynchronous one-to-many communication with all other BroadcastChannel instances bound to the same channel name.

import {
  isMainThread,
  BroadcastChannel,
  Worker,
} from 'node:worker_threads';

const bc = new BroadcastChannel('hello');

if (isMainThread) {
  let c = 0;
  bc.onmessage = (event) => {
    console.log(event.data);
    if (++c === 10) bc.close();
  };
  for (let n = 0; n < 10; n++)
    new Worker(new URL(import.meta.url));
} else {
  bc.postMessage('hello from every worker');
  bc.close();
}
const {
  isMainThread,
  BroadcastChannel,
  Worker,
} = require('node:worker_threads');

const bc = new BroadcastChannel('hello');

if (isMainThread) {
  let c = 0;
  bc.onmessage = (event) => {
    console.log(event.data);
    if (++c === 10) bc.close();
  };
  for (let n = 0; n < 10; n++)
    new Worker(__filename);
} else {
  bc.postMessage('hello from every worker');
  bc.close();
}
C

BroadcastChannel Constructor

History
new BroadcastChannel(name): BroadcastChannel
Attributes
name:any
The name of the channel to connect to. Any JavaScript value that can be converted to a string using `${name}` is permitted.
M

broadcastChannel.close

History
broadcastChannel.close(): void

Closes the BroadcastChannel connection.

P

broadcastChannel.onmessage

History
Invoked with a single MessageEvent argument when a message is received.
P

broadcastChannel.onmessageerror

History
Invoked with a received message cannot be deserialized.
M

broadcastChannel.postMessage

History
broadcastChannel.postMessage(message): void
Attributes
message:any
Any cloneable JavaScript value.
M

broadcastChannel.ref

History
broadcastChannel.ref(): void

Opposite of unref(). Calling ref() on a previously unref()ed BroadcastChannel does not let the program exit if it's the only active handle left (the default behavior). If the port is ref()ed, calling ref() again has no effect.

M

broadcastChannel.unref

History
broadcastChannel.unref(): void

Calling unref() on a BroadcastChannel allows the thread to exit if this is the only active handle in the event system. If the BroadcastChannel is already unref()ed calling unref() again has no effect.