Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions lib/internal/worker/io.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ const {
} = internalBinding('messaging');
const {
getEnvMessagePort,
threadId,
} = internalBinding('worker');

const { Readable, Writable } = require('stream');
Expand Down Expand Up @@ -346,7 +347,7 @@ function receiveMessageOnPort(port) {
}

function onMessageEvent(type, data) {
this.dispatchEvent(lazyMessageEvent(type, { data }));
this.dispatchEvent(lazyMessageEvent(type, { data: data.value, source: data.source }));
}

function isBroadcastChannel(value) {
Expand Down Expand Up @@ -419,13 +420,17 @@ class BroadcastChannel extends EventTarget {
* @returns {void}
*/
postMessage(message) {
const broadcastMessage = {
source: threadId,
value: message,
};
if (!isBroadcastChannel(this))
throw new ERR_INVALID_THIS('BroadcastChannel');
if (arguments.length === 0)
throw new ERR_MISSING_ARGS('message');
if (this[kHandle] === undefined)
throw new DOMException('BroadcastChannel is closed.', 'InvalidStateError');
if (this[kHandle].postMessage(message) === undefined)
if (this[kHandle].postMessage(broadcastMessage) === undefined)
throw new DOMException('Message could not be posted.');
}

Expand Down
31 changes: 30 additions & 1 deletion test/parallel/test-worker-broadcastchannel.js
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ assert.throws(() => new BroadcastChannel(), {
const bc1 = new BroadcastChannel('channel4');
const bc2 = new BroadcastChannel('channel4');
bc1.postMessage('some data');
assert.strictEqual(receiveMessageOnPort(bc2).message, 'some data');
assert.strictEqual(receiveMessageOnPort(bc2).message.value, 'some data');
assert.strictEqual(receiveMessageOnPort(bc2), undefined);
bc1.close();
bc2.close();
Expand Down Expand Up @@ -183,3 +183,32 @@ assert.throws(() => new BroadcastChannel(), {
"BroadcastChannel { name: 'channel5', active: false }"
);
}

{
const bc = new BroadcastChannel('worker-source');

new Worker(`
const assert = require('assert');
const { BroadcastChannel, threadId } = require('worker_threads');

const bc = new BroadcastChannel('worker-source');

bc.onmessage = (evt) => {
assert.strictEqual(evt.data, 'from-main');
assert.strictEqual(evt.source, 0);

bc.close();
};

bc.postMessage('from-worker');
`, { eval: true });

bc.onmessage = common.mustCall((evt) => {
assert.strictEqual(evt.data, 'from-worker');

assert.ok(evt.source > 0);

bc.postMessage('from-main');
bc.close();
});
}
Loading