Web/API/RTCDataChannel/onmessage

From Get docs

This is an experimental technologyCheck the Browser compatibility table carefully before using this in production.


The RTCDataChannel.onmessage property stores an EventHandler 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

Specification Status Comment
WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCDataChannel.onmessage' in that specification. Candidate Recommendation Initial specification.

Browser compatibility

Update compatibility data on GitHub

Desktop Mobile
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet

onmessage

Experimental'

Chrome

Full support 56

Edge

Full support ≤79

Firefox

Full support Yes

IE

No support No

Opera

Full support 43

Safari

Full support Yes

WebView Android

Full support 56

Chrome Android

Full support 56

Firefox Android

Full support Yes

Opera Android

Full support 43

Safari iOS

Full support Yes

Samsung Internet Android

Full support 6.0

Legend

Full support  
Full support
No support  
No support
Experimental. Expect behavior to change in the future.'
Experimental. Expect behavior to change in the future.


See also