demo · v130
Transfer RTCDataChannel to a worker
The "run" button creates two peers in a single page, opens a data channel between them, then transfers the receiving end to a dedicated worker. The worker reads and echoes back messages — all off the main thread.
the code
const pc1 = new RTCPeerConnection();
const pc2 = new RTCPeerConnection();
const ch = pc1.createDataChannel("chat");
// negotiate pc1 <-> pc2 …
// On the receiving side:
pc2.ondatachannel = (ev) => {
const worker = new Worker("./chat-worker.js");
worker.postMessage({ ch: ev.channel }, [ev.channel]); // ← v130: transferable
};
// chat-worker.js
onmessage = ({ data }) => {
const ch = data.ch;
ch.onmessage = (e) => ch.send("echo: " + e.data);
};
see also
- Transferable RTCDataChannel to workers — feature index
- ChromeStatus entry