--- title: RTCPeerConnection.ondatachannel slug: Web/API/RTCPeerConnection/ondatachannel translation_of: Web/API/RTCPeerConnection/ondatachannel ---

{{APIRef("WebRTC")}}{{SeeCompatTable}}

RTCPeerConnection.ondatachannel 属性是一个{{event("Event_handlers", "event handler")}},当这个{{event("datachannel")}}事件在{{domxref("RTCPeerConnection")}}发生时,它指定的那个事件处理函数就会被调用。这个事件继承于 {{domxref("RTCDataChannelEvent")}},当远方伙伴调用{{domxref("RTCPeerConnection.createDataChannel", "createDataChannel()")}}时这个事件被加到这个连接(RTCPeerConnection)中。

在这个事件被收到的同时,这个{{domxref("RTCDataChannel")}} 实际上并没有打开,确保在open这个事件在RTCDataChannel触发以后才去使用它。

语法

RTCPeerConnection.ondatachannel = function;

将这个属性设置为接受一个参数的函数:这个参数是一个{{domxref("RTCDataChannelEvent")}},它的channel属性是一个已经创建了的{{domxref("RTCDataChannel")}}对象

示例

pc.ondatachannel = function(ev) {
  console.log('Data channel is created!');
  ev.channel.onopen = function() {
    console.log('Data channel is open and ready to be used.');
  };
};

规范

Specification Status Comment
{{ SpecName('WebRTC 1.0', '#dom-rtcpeerconnection-ondatachannel', 'RTCPeerConnection.ondatachannel') }} {{ Spec2('WebRTC 1.0') }} Initial specification.

浏览器支持

{{ CompatibilityTable}}

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support {{ CompatVersionUnknown}} [1] {{ CompatGeckoDesktop(18) }} [2] {{ CompatNo}} {{ CompatVersionUnknown}} {{ CompatUnknown}}
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support {{ CompatUnknown}} {{ CompatUnknown}} {{ CompatGeckoMobile(22) }} [2] {{ CompatNo}} {{ CompatUnknown}} {{ CompatUnknown}}

[1] Though this property is not prefixed, the interface it belongs to is.

[2] This property's name isn't prefixed, but the interface it's in, {{domxref("RTCPeerConnection")}}, was prefixed as MozRTCPeerConnection until Firefox 44.

相关阅读