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

{{APIRef}}{{SeeCompatTable}}

The RTCPeerConnection interface represents a WebRTC connection between the local computer and a remote peer. It is used to handle efficient streaming of data between the two peers.

Note: RTCPeerConnection and {{domxref("RTCSessionDescription")}} are currently prefixed in most browsers, and the {{domxref("navigator.getUserMedia()")}} method is prefixed in many versions of some browsers; you should use code like the following to access these:

var peerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection ||
                       window.webkitRTCPeerConnection || window.msRTCPeerConnection;
var sessionDescription = window.RTCSessionDescription || window.mozRTCSessionDescription ||
                       window.webkitRTCSessionDescription || window.msRTCSessionDescription;

navigator.getUserMedia = navigator.getUserMedia || navigator.mozGetUserMedia ||
                       navigator.webkitGetUserMedia || navigator.msGetUserMedia;

Simple code such as this is all it takes to ensure that your project will work on as many versions of as many browsers as possible.

Basic usage

Basic RTCPeerConnection usage involves negotiating a connection between your local machine and a remote one by generating Session Description Protocol to exchange between the two. The caller starts the process by sending an offer to the remote machine, which responds by either accepting or rejecting the call.

Both parties (the caller and the called party) need to set up their own RTCPeerConnection instances to represent their end of the peer-to-peer connection:

var pc = new RTCPeerConnection();
pc.onaddstream = function(obj) {
  var vid = document.createElement("video");
  document.appendChild(vid);
  vid.srcObject = obj.stream;
}

// Helper functions
function endCall() {
  var videos = document.getElementsByTagName("video");
  for (var i = 0; i < videos.length; i++) {
    videos[i].pause();
  }

  pc.close();
}

function error(err) {
  endCall();
}

Initializing the call

If you are the one initiating the call, you would use {{domxref("navigator.getUserMedia()")}} to get a video stream, then add the stream to the RTCPeerConnection. Once that's been done, call {{domxref("RTCPeerConnection.createOffer()")}} to create an offer, configure the offer, then send it to the server through which the connection is being mediated.

// Get a list of friends from a server
// User selects a friend to start a peer connection with
navigator.getUserMedia({video: true}, function(stream) {
  // Adding a local stream won't trigger the onaddstream callback,
  // so call it manually.
  pc.onaddstream({stream: stream});
  pc.addStream(stream);

  pc.createOffer(function(offer) {
    pc.setLocalDescription(new RTCSessionDescription(offer), function() {
      // send the offer to a server to be forwarded to the friend you're calling.
    }, error);
  }, error);
});

Answering a call

On the opposite end, the friend will receive the offer from the server using whatever protocol is being used to do so. Once the offer arrives, {{domxref("navigator.getUserMedia()")}} is once again used to create the stream, which is added to the RTCPeerConnection. An {{domxref("RTCSessionDescription")}} object is created and set up as the remote description by calling {{domxref("RTCPeerConnection.setRemoteDescription()")}}.

Then an answer is created using {{domxref("RTCPeerConnection.createAnswer()")}} and sent back to the server, which forwards it to the caller.

var offer = getOfferFromFriend();
navigator.getUserMedia({video: true}, function(stream) {
  pc.onaddstream({stream: stream});
  pc.addStream(stream);

  pc.setRemoteDescription(new RTCSessionDescription(offer), function() {
    pc.createAnswer(function(answer) {
      pc.setLocalDescription(new RTCSessionDescription(answer), function() {
        // send the answer to a server to be forwarded back to the caller (you)
      }, error);
    }, error);
  }, error);
});

Handling the answer

Back on the original machine, the response is received. Once that happens, call {{domxref("RTCPeerConnection.setRemoteDescription()")}} to set the response as the remote end of the connection.

// pc was set up earlier when we made the original offer
var offer = getResponseFromFriend();
pc.setRemoteDescription(new RTCSessionDescription(offer), function() { }, error);

Constructor

{{domxref("RTCPeerConnection.RTCPeerConnection", "RTCPeerConnection()")}}
Constructor; returns a new RTCPeerConnection object.

Properties

This interface inherits properties from its parent interface, {{domxref("EventTarget")}}.

{{domxref("RTCPeerConnection.iceConnectionState")}} {{ReadOnlyInline}}
Returns an enum of type RTCIceConnectionState that describes the ICE connection state for the connection. When this value changes, a {{event("iceconnectionstatechange")}} event is fired on the object.
{{domxref("RTCPeerConnection.iceGatheringState")}} {{ReadOnlyInline}}
Returns an enum of type RTCIceGatheringState that describes the ICE gathering state for the connection.
{{domxref("RTCPeerConnection.localDescription")}} {{ReadOnlyInline}}
Returns a {{domxref("RTCSessionDescription")}} describing the session for the local end of the connection. If it has not yet been set, it can be null.
{{domxref("RTCPeerConnection.peerIdentity")}} {{ReadOnlyInline}}
Returns a RTCIdentityAssertion, that is a couple of a domain name (idp) and a name (name) representing the identity of the remote peer of this connection, once set and verified. If no peer has yet been set and verified, this property will return null. Once set, via the appropriate method, it can't be changed.
{{domxref("RTCPeerConnection.remoteDescription")}} {{ReadOnlyInline}}
Returns a {{domxref("RTCSessionDescription")}} describing the session for the remote end of the connection. If it has not yet been set, it can be null.
{{domxref("RTCPeerConnection.signalingState")}} {{ReadOnlyInline}}
Returns an enum of type RTCSignalingState that describes the signaling state of the local connection. This state describes the SDP offer, that defines the configuration of the connections like the description of the locally associated objects of type {{domxref("MediaStream")}}, the codec/RTP/RTCP options, the candidates gathered by the ICE Agent. When this value changes, a {{event("signalingstatechange")}} event is fired on the object.

Event handlers

{{domxref("RTCPeerConnection.onaddstream")}}
Is the event handler called when the {{event("addstream")}} event is received. Such an event is sent when a {{domxref("MediaStream")}} is added to this connection by the remote peer. The event is sent immediately after the call {{domxref("RTCPeerConnection.setRemoteDescription()")}} and doesn't wait for the result of the SDP negotiation.
{{domxref("RTCPeerConnection.ondatachannel")}}
Is the event handler called when the {{event("datachannel")}} event is received. Such an event is sent when a {{domxref("RTCDataChannel")}} is added to this connection.
{{domxref("RTCPeerConnection.onicecandidate")}}
Is the event handler called when the {{event("icecandidate")}} event is received. Such an event is sent when a {{domxref("RTCICECandidate")}} object is added to the script.
{{domxref("RTCPeerConnection.oniceconnectionstatechange")}}
Is the event handler called when the {{event("iceconnectionstatechange")}} event is received. Such an event is sent when the value of {{domxref("RTCPeerConnection.iceConnectionState", "iceConnectionState")}} changes.
{{domxref("RTCPeerConnection.onidentityresult")}}
Is the event handler called when the {{event("identityresult")}} event is received. Such an event is sent when an identity assertion is generated, via {{domxref("RTCPeerConnection.getIdentityAssertion()", "getIdentityAssertion()")}}, or during the creation of an offer or an answer.
{{domxref("RTCPeerConnection.onidpassertionerror")}}
Is the event handler called when the {{event("idpassertionerror")}} event is received. Such an event is sent when the associated identity provider (IdP) encounters an error while generating an identity assertion.
{{domxref("RTCPeerConnection.onidpvalidationerror")}}
Is the event handler alled when the {{event("idpvalidationerror")}} event is received. Such an event is sent when the associated identity provider (IdP) encounters an error while validating an identity assertion.
{{domxref("RTCPeerConnection.onnegotiationneeded")}}
Is the event handler called when the {{event("negotiationneeded")}} event, sent by the browser to inform that negotiation will be required at some point in the future, is received.
{{domxref("RTCPeerConnection.onpeeridentity")}}
Is the event handler called when the {{event("peeridentity")}} event, sent when a peer identity has been set and verified on this connection, is received.
{{domxref("RTCPeerConnection.onremovestream")}}
Is the event handler called when the {{event("removestream")}} event, sent when a {{domxref("MediaStream")}} is removed from this connection, is received.
{{domxref("RTCPeerConnection.onsignalingstatechange")}}
Is the event handler called when the {{event("signalingstatechange")}} event, sent when the value of {{domxref("RTCPeerConnection.signalingState", "signalingState")}} changes, is received.

Methods

{{domxref("RTCPeerConnection.addIceCandidate()")}}
 
{{domxref("RTCPeerConnection.addStream()")}}
Adds a {{domxref("MediaStream")}} as a local source of audio or video. If the negotiation already happened, a new one will be needed for the remote peer to be able to use it.
{{domxref("RTCPeerConnection.close()")}}
Abruptly closes a connection.
{{domxref("RTCPeerConnection.createAnswer()")}}
Creates an answer to the offer received by the remote peer, in a two-part offer/answer negotiation of a connection. The two first parameters are respectively success and error callbacks, the optional third one represent options for the answer to be created.
{{domxref("RTCPeerConnection.createDataChannel()")}}
Creates a new {{domxref("RTCDataChannel")}} associated with this connection. The method takes a dictionary as parameter, with the configuration required for the underlying data channel, like its reliability.
{{domxref("RTCPeerConnection.createDTMFSender()")}}
Creates a new {{domxref("RTCDTMFSender")}}, associated to a specific {{domxref("MediaStreamTrack")}}, that will be able to send {{Glossary("DTMF")}} phone signaling over the connection.
{{domxref("RTCPeerConnection.createOffer()")}}
Creates a request to find a remote peer with a specific configuration. 
{{domxref("RTCPeerConnection.generateCertificate()")}}
Creates and stores an X.509 certificate and corresponding private key then returns an {{domxref("RTCCertificate")}}, providing access to it.
{{domxref("RTCPeerConnection.getConfiguration()")}}
 
{{domxref("RTCPeerConnection.getIdentityAssertion()")}}
Initiates the gathering of an identity assertion. This has an effect only if the {{domxref("RTCPeerConnection.signalingState", "signalingState")}} is not "closed". It is not expected for the application dealing with the RTCPeerConnection: this is automatically done; an explicit call only allows to anticipate the need.
{{domxref("RTCPeerConnection.getLocalStreams()")}}
Returns an array of {{domxref("MediaStream")}} associated with the local end of the connection. The array may be empty.
{{domxref("RTCPeerConnection.getRemoteStreams()")}}
Returns an array of {{domxref("MediaStream")}} associated with the remote end of the connection. The array may be empty.
{{domxref("RTCPeerConnection.getStats()")}}
Creates a new {{domxref("RTCStatsReport")}} that contains and allows access to statistics regarding the connection.
{{domxref("RTCPeerConnection.getStreamById()")}}
Returns the {{domxref("MediaStream")}} with the given id that is associated with local or remote end of the connection. If no stream matches, it returns null.
{{domxref("RTCPeerConnection.removeStream()")}}
Removes a {{domxref("MediaStream")}} as a local source of audio or video. If the negotiation already happened, a new one will be needed for the remote peer to stop using it.
{{domxref("RTCPeerConnection.setIdentityProvider()")}}
Sets the Identity Provider (IdP) to the triplet given in parameter: its name, the protocol used to communicate with it (optional) and an optional username. The IdP will be used only when an assertion will be needed.
{{domxref("RTCPeerConnection.setLocalDescription()")}}
Changes the local description associated with the connection. The description defines the properties of the connection like its codec. The connection is affected by this change and must be able to support both old and new descriptions. The method takes three parameters, a {{domxref("RTCSessionDescription")}} object to set, and two callbacks, one called if the change of description succeeds, another called if it failed.
{{domxref("RTCPeerConnection.setRemoteDescription()")}}
Changes the remote description associated with the connection. The description defines the properties of the connection like its codec. The connection is affected by this change and must be able to support both old and new descriptions. The method takes three parameters, a {{domxref("RTCSessionDescription")}} object to set, and two callbacks, one called if the change of description succeeds, another called if it failed.
{{domxref("RTCPeerConnection.updateIce()")}}
 

Constructor

new RTCPeerConnection({{domxref("RTCConfiguration")}} configuration, optional {{domxref("MediaConstraints")}} constraints);

Note: While the PeerConnection specification reads like passing an RTCConfiguration object is required, Firefox will supply a default if you don't.

Methods

createOffer

void createOffer({{domxref("RTCSessionDescriptionCallback")}} successCallback, {{domxref("RTCPeerConnectionErrorCallback")}} failureCallback, optional {{domxref("MediaConstraints")}} constraints);

Create offer generates a blob of description data to facilitate a PeerConnection to the local machine. Use this when you've got a remote Peer connection and you want to set up the local one.

Example

var pc = new PeerConnection();
pc.addStream(video);
pc.createOffer(function(desc){
  pc.setLocalDescription(desc, function() {
    // send the offer to a server that can negotiate with a remote client
  });
}

Arguments

successCallback
An {{domxref("RTCSessionDescriptionCallback")}} which will be passed a single {{domxref("RTCSessionDescription")}} object
errorCallback
An {{domxref("RTCPeerConnectionErrorCallback")}} which will be passed a single {{domxref("DOMError")}} object
[optional] constraints
An optional {{domxref("MediaConstraints")}} object.

createAnswer

void createAnswer({{domxref("RTCSessionDescriptionCallback")}} successCallback, {{domxref("RTCPeerConnectionErrorCallback")}} failureCallback, optional {{domxref("MediaConstraints")}} constraints)")

Respond to an offer sent from a remote connection.

Example

var pc = new PeerConnection();
pc.setRemoteDescription(new RTCSessionDescription(offer), function() {
  pc.createAnswer(function(answer) {
    pc.setLocalDescription(answer, function() {
      // send the answer to the remote connection
    })
  })
});

Arguments

successCallback
An {{domxref("RTCSessionDescriptionCallback")}} which will be passed a single {{domxref("RTCSessionDescription")}} object
errorCallback
An {{domxref("RTCPeerConnectionErrorCallback")}} which will be passed a single {{domxref("DOMError")}} object
[optional] constraints
An optional {{domxref("MediaConstraints")}} object.

updateIce()

updateIce(optional {{domxref("RTCConfiguration")}} configuration, optional {{domxref("MediaConstraints")}} constraints)

The updateIce method updates the ICE Agent process of gathering local candidates and pinging remote candidates. If there is a mandatory constraint called "IceTransports" it will control how the ICE engine can act. This can be used to limit the use to TURN candidates by a callee to avoid leaking location information prior to the call being accepted. This call may result in a change to the state of the ICE Agent, and may result in a change to media state if it results in connectivity being established.

Example

 

addIceCandidate()

addIceCandidate ({{domxref("RTCIceCandidate")}} candidate, {{domxref("Function")}} successCallback, {{domxref("RTCPeerConnectionErrorCallback")}} failureCallback);

The addIceCandidate() method provides a remote candidate to the ICE Agent. In addition to being added to the remote description, connectivity checks will be sent to the new candidates as long as the "IceTransports" constraint is not set to "none". This call will result in a change to the connection state of the ICE Agent, and may result in a change to media state if it results in different connectivity being established.

Example

  pc.addIceCandidate(new RTCIceCandidate(candidate));

createDataChannel

{{domxref("RTCDataChannel")}} createDataChannel ({{domxref("DOMString")}} label, optional {{domxref("RTCDataChannelInit")}} dataChannelDict);

Creates a data channel for sending non video or audio data across the peer connection

Example

var pc = new PeerConnection();
var channel = pc.createDataChannel("Mydata");
channel.onopen = function(event) {
  channel.send('sending a message');
}
channel.onmessage = function(event) { console.log(event.data); }

Specifications

Specification Status Comment
{{SpecName('WebRTC 1.0')}} {{Spec2('WebRTC 1.0')}} Initial definition.

Browser compatibility

{{CompatibilityTable}}
Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support {{CompatVersionUnknown}}        
Feature Android Android Webview Firefox Mobile (Gecko) Firefox OS IE Mobile Opera Mobile Safari Mobile Chrome for Android
Basic support {{CompatNo}} {{CompatVersionUnknown}}           {{CompatVersionUnknown}}

See also