RTCDataChannel: send() method
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since January 2020.
Thesend() method of theRTCDataChannel interface sends data across the data channel to theremote peer.This can be done any time except during the initial process ofcreating the underlying transport channel. Data sent before connecting is buffered ifpossible (or an error occurs if it's not possible), and is also buffered if sent whilethe connection is closing or closed.
Note:Different browsers have different limitations on the size of the message you cansend. Specifications exist to define how to automatically fragment large messages, butnot all browsers implement them, and those that do have various additionalrestrictions. This will get less complicated over time, but for now, if you havequestions, seeUnderstanding message size limits.
In this article
Syntax
send(data)Parameters
dataThe data to transmit across the connection. This may be a string,a
Blob, anArrayBuffer, aTypedArrayor aDataViewobject.
Return value
None (undefined).
Exceptions
InvalidStateErrorDOMExceptionThrown when the data channel has not finished establishing its own connection (that is, its
readyStateisconnecting). The data channelmust establish its own connection because it uses a transport channel separate from that of the media content. This error occurs without sending or buffering thedata.OperationErrorDOMExceptionThrown when the specified
datawould need to be buffered, and there isn't room for it in the buffer.TypeErrorThrown if the specified
datais too large for the other peer to receive. Sincethere are multiple techniques for breaking up large data into smaller pieces fortransfer, it's possible to encounter scenarios in which the other peer does notsupport the same ones. For example, if one peer is a modern browser that supportsusing theEOR(End of Record) flag to indicate when a received message isthe last piece of a multi-part object sent usingsend(). For moreinformation about message size restrictions, seeUnderstanding message size limits.
Examples
In this example, a routine calledsendMessage() is created; it accepts anobject as input and sends to the remote peer, over theRTCDataChannel, aJSON string with the specified object and a timestamp.
const pc = new RTCPeerConnection();const dc = pc.createDataChannel("BackChannel");function sendMessage(msg) { const obj = { message: msg, timestamp: new Date(), }; dc.send(JSON.stringify(obj));}Specifications
| Specification |
|---|
| WebRTC: Real-Time Communication in Browsers> # dom-rtcdatachannel-send> |