files/en-us/web/api/rtcpeerconnection/datachannel_event/index.md
{{APIRef("WebRTC")}}
A datachannel event is sent to an {{domxref("RTCPeerConnection")}} instance when an {{domxref("RTCDataChannel")}} has been added to the connection, as a result of the remote peer calling {{domxref("RTCPeerConnection.createDataChannel()")}}.
[!NOTE] This event is not dispatched when the local end of the connection creates the channel.
This event is not cancelable and does not bubble.
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
addEventListener("datachannel", (event) => { })
ondatachannel = (event) => { }
An {{domxref("RTCDataChannelEvent")}}. Inherits from {{domxref("Event")}}.
{{InheritanceDiagram("RTCDataChannelEvent")}}
Also inherits properties from {{DOMxRef("Event")}}.
This example sets up a function that handles datachannel events by gathering the information needed to communicate with the newly added {{domxref("RTCDataChannel")}} and by adding event handlers for the events that occur on that channel.
pc.addEventListener("datachannel", (ev) => {
receiveChannel = ev.channel;
receiveChannel.onmessage = myHandleMessage;
receiveChannel.onopen = myHandleOpen;
receiveChannel.onclose = myHandleClose;
});
receiveChannel is set to the value of the event's {{domxref("RTCDataChannelEvent.channel", "channel")}} property, which specifies the RTCDataChannel object representing the data channel linking the remote peer to the local one.
This same code can also instead use the {{domxref("RTCPeerConnection")}} interface's ondatachannel event handler property, like this:
pc.ondatachannel = (ev) => {
receiveChannel = ev.channel;
receiveChannel.onmessage = myHandleMessage;
receiveChannel.onopen = myHandleOpen;
receiveChannel.onclose = myHandleClose;
};
{{Specifications}}
{{Compat}}