W3cubDocs

/Web APIs

RTCDataChannel.onmessage

The RTCDataChannel.onmessage property stores an event handler which specifies a function to be called when the message event is fired on the channel. This event is represented by the MessageEvent interface. This event is sent to the channel when a message is received from the other peer.

Syntax

RTCDataChannel.onmessage = function;

Value

A function which the browser will call to handle the message event. The function receives as its sole input parameter a MessageEvent object describing the event.

Example

This code snippet creates a peer connection, adds a data channel to it, and starts creating new <p> (paragraph) elements each time a message arrives, with the message's contents displayed inside it. The new elements are then attached to the end of the document.

let pc = new RTCPeerConnection();
let dc = pc.createDataChannel();

dc.onmessage = function(event) {
  var el = document.createElement("p");
  var txtNode = document.createTextNode(event.data);

  el.appendChild(txtNode);
  receiveBox.appendChild(el);
}

Specifications

Browser compatibility

Desktop Mobile
Chrome Edge Firefox Internet Explorer Opera Safari WebView Android Chrome Android Firefox for Android Opera Android Safari on IOS Samsung Internet
onmessage
24
79
22
No
15
11
≤37
25
22
14
11
1.5

See also

© 2005–2021 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/RTCDataChannel/onmessage