RTCPeerConnection: sctp property - Web APIs

RTCPeerConnection: sctp property
================================

 The read-only **`sctp`** property on the `RTCPeerConnection` interface returns an `RTCSctpTransport` describing the SCTP transport over which SCTP data is being sent and
 received.
 If SCTP hasn't been negotiated, this value is `null`.

The SCTP transport is used for transmitting and receiving data for any and all `RTCDataChannel`s on the peer connection.

Value
-----

A `RTCSctpTransport` object describing the SCTP transport being used by the `RTCPeerConnection` for transmitting and receiving on its data channels, or `null` if SCTP negotiation hasn't happened.

Example
-------

```js
const peerConnection = new RTCPeerConnection();

const channel = peerConnection.createDataChannel("Mydata");
channel.onopen = (event) => {
  channel.send("sending a message");
};
channel.onmessage = (event) => {
  console.log(event.data);
};

// Determine the largest message size that can be sent

const sctp = peerConnection.sctp;
const maxMessageSize = sctp.maxMessageSize;
```

Specifications
--------------

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-rtcpeerconnection-sctp |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebRTC
* `RTCPeerConnection`
* `RTCDataChannel`
* SCTP


RTCPeerConnection: createAnswer() method - Web APIs

RTCPeerConnection: createAnswer() method
========================================

 The **`createAnswer()`** method on the
 `RTCPeerConnection` interface creates an SDP answer to an
 offer received from a remote peer during the offer/answer negotiation of a WebRTC
 connection. The answer contains information about any media already attached to the
 session, codecs and options supported by the browser, and any ICE
 candidates already gathered. The answer is delivered to the returned
 `Promise`, and should then be sent to the source of the offer to continue
 the negotiation process.

Syntax
------

```js
createAnswer()
createAnswer(options)

createAnswer(successCallback, failureCallback) // deprecated
createAnswer(successCallback, failureCallback, options) // deprecated
```

### Parameters

`options` Optional

An optional object providing options requested for the answer. Currently, there are no available options.

### Deprecated parameters

 In older code and documentation, you may see a callback-based version of this function.
 This has been deprecated and its use is **strongly** discouraged. You
 should update any existing code to use the `Promise`-based version of
 `createAnswer()` instead. The parameters for the older form of
 `createAnswer()` are described below, to aid in updating existing code.

`successCallback`
Deprecated

 A callback function which will be passed a single
 `RTCSessionDescription` object describing the newly-created answer.

`failureCallback`
Deprecated

 A callback function which will be passed a single
 `DOMException` object explaining why the request to create an answer
 failed.

`options` Optional

An optional object providing options requested for the answer.

### Exceptions

`NotReadableError`

The identity provider wasn't able to provide an identity assertion.

`OperationError`

 Generation of the SDP failed for some reason; this is a general failure catch-all
 exception.

### Return value

 A `Promise` whose fulfillment handler is called with an object conforming
 to the `RTCSessionDescriptionInit` dictionary which contains the SDP answer
 to be delivered to the other peer.

Examples
--------

 Here is a segment of code taken from the code that goes with the article Signaling and video calling. This code comes from the handler for the message sent to carry an offer
 to another peer across the signaling channel.

**Note:** Keep in mind that this is part of the signaling process, the transport layer for
 which is an implementation detail that's entirely up to you. In this case, a WebSocket connection is used to send a
 JSON message with a `type` field with the value
 "video-answer" to the other peer, carrying the answer to the device which sent the
 offer to connect. The contents of the object being passed to the
 `sendToServer()` function, along with everything else in the promise
 fulfillment handler, depend entirely on your design

```js
pc.createAnswer()
  .then((answer) => pc.setLocalDescription(answer))
  .then(() => {
    // Send the answer to the remote peer through the signaling server.
  })
  .catch(handleGetUserMediaError);
```

 This asks `RTCPeerConnection` to create and return a new answer. In our
 promise handler, the returned answer is set as the description of the local end of the
 connection by calling `setLocalDescription()`.

 Once that succeeds, the answer is sent to the signaling server using whatever protocol
 you see fit.

`Promise.catch()` is used to trap and handle errors.

 See Handling the invitation in our WebRTC chat example to view the complete code from which this
 snippet is derived; that will help you understand the signaling process and how answers
 work.

Specifications
--------------

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-rtcpeerconnection-createanswer |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


RTCPeerConnection: track event - Web APIs

RTCPeerConnection: track event
==============================

The **`track`** event is sent to the `ontrack` event handler on `RTCPeerConnection`s after a new track has been added to an `RTCRtpReceiver` which is part of the connection.

By the time this event is delivered, the new track has been fully added to the peer connection. See Track event types for details.

This event is not cancellable and does not bubble.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("track", (event) => {});

ontrack = (event) => {};
```

Event type
----------

An `RTCTrackEvent`. Inherits from `Event`.

Event

RTCTrackEventEvent properties
----------------

*Since `RTCTrackEvent` is based on `Event`, its properties are also available.*

`receiver` Read only

The `RTCRtpReceiver` used by the track that's been added to the `RTCPeerConnection`.

`streams` Read only  Optional

An array of `MediaStream` objects, each representing one of the media streams to which the added `track` belongs. By default, the array is empty, indicating a streamless track.

`track` Read only

The `MediaStreamTrack` which has been added to the connection.

`transceiver` Read only

The `RTCRtpTransceiver` being used by the new track.

Examples
--------

This example shows code that creates a new `RTCPeerConnection`, then adds a new `track` event handler.

```js
pc = new RTCPeerConnection({
  iceServers: [
    {
      urls: "turn:fake.turnserver.url",
      username: "someusername",
      credential: "somepassword",
    },
  ],
});

pc.addEventListener(
  "track",
  (e) => {
    videoElement.srcObject = e.streams[0];
    hangupButton.disabled = false;
  },
  false,
);
```

The event handler assigns the new track's first stream to an existing `<video>` element, identified using the variable `videoElement`.

You can also assign the event handler function to the `ontrack` property, rather than use `addEventListener()`.

```js
pc.ontrack = (e) => {
  videoElement.srcObject = e.streams[0];
  hangupButton.disabled = false;
  return false;
};
```

Specifications
--------------

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # event-track |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


RTCPeerConnection: setIdentityProvider() method - Web APIs

RTCPeerConnection: setIdentityProvider() method
===============================================

 The **`RTCPeerConnection.setIdentityProvider()`** method 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 is needed.

 If the `signalingState` is set to
 `"closed"`, an `InvalidStateError` is raised.

Syntax
------

```js
setIdentityProvider(domainname)
setIdentityProvider(domainname, protocol)
setIdentityProvider(domainname, protocol, username)
```

### Parameters

`domainname`

A string representing the domain name where the IdP is.

`protocol` Optional

 A string representing the protocol used to communicate with the
 IdP. It defaults to `"default"` and is used to determine the URL where the
 IdP is listening.

`username` Optional

A string representing the username associated with the IdP.

### Return value

None (`undefined`).

Example
-------

```js
const pc = new RTCPeerConnection();

pc.setIdentityAssertion("developer.mozilla.org");
```

Specifications
--------------

| Specification |
| --- |
| Identity for WebRTC 1.0 # dom-rtcpeerconnection-setidentityprovider |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebRTC


RTCPeerConnection: icecandidate event - Web APIs

RTCPeerConnection: icecandidate event
=====================================

An **`icecandidate`** event is sent to an `RTCPeerConnection` when:

* An `RTCIceCandidate` has been identified and added to the local peer by a call to `RTCPeerConnection.setLocalDescription()`,
* Every `RTCIceCandidate` correlated with a particular username fragment and password combination (a **generation**) has been so identified and added, and
* All ICE gathering on all transports is complete.

In the first two cases, the event handler should transmit the candidate to the remote peer over the signaling channel so the remote peer can add it to its set of remote candidates.

This event is not cancelable and does not bubble.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("icecandidate", (event) => {});

onicecandidate = (event) => {};
```

Event type
----------

An `RTCPeerConnectionIceEvent`. Inherits from `Event`.

Event

RTCPeerConnectionIceEventEvent properties
----------------

*A `RTCPeerConnectionIceEvent` being an `Event`, this event also implements the following property*.

`RTCPeerConnectionIceEvent.candidate` Read only

 Indicates the `RTCIceCandidate` containing the candidate associated with the event.
 This will be the empty string if the event indicates that there are no further candidates to come in this **generation**, or `null` if all ICE gathering on all transports is complete.

Description
-----------

There are three reasons why the `icecandidate` event is fired on an `RTCPeerConnection`.

### Sharing a new candidate

The majority of `icecandidate` events are fired to indicate that a new candidate has been gathered. This candidate needs to be delivered to the remote peer over the signaling channel your code manages.

```js
rtcPeerConnection.onicecandidate = (event) => {
  if (event.candidate !== null) {
    sendCandidateToRemotePeer(event.candidate);
  } else {
    /\* there are no more candidates coming during this negotiation \*/
  }
};
```

The remote peer, upon receiving the candidate, will add the candidate to its candidate pool by calling `addIceCandidate()`, passing in the `candidate` string you have passed along using the signaling server.

### Indicating the end of a generation of candidates

When an ICE negotiation session runs out of candidates to propose for a given `RTCIceTransport`, it has completed gathering for a **generation** of candidates. That this has occurred is indicated by an `icecandidate` event whose `candidate` string is empty (`""`).

You should deliver this to the remote peer just like any standard candidate, as described under Sharing a new candidate above. This ensures that the remote peer is given the end-of-candidates notification as well. As you see in the code in the previous section, every candidate is sent to the other peer, including any that might have an empty candidate string. Only candidates for which the event's `candidate` property is `null` are not forwarded across the signaling connection.

The end-of-candidates indication is described in section 9.3 of the Trickle ICE draft specification (note that the section number is subject to change as the specification goes through repeated drafts).

### Indicating that ICE gathering is complete

Once all ICE transports have finished gathering candidates and the value of the `RTCPeerConnection` object's `iceGatheringState` has made the transition to `complete`, an `icecandidate` event is sent with the value of `candidate` set to `null`.

This signal exists for backward compatibility purposes and does *not* need to be delivered onward to the remote peer (which is why the code snippet above checks to see if `event.candidate` is `null` prior to sending the candidate along).

If you need to perform any special actions when there are no further candidates expected, you're much better off watching the ICE gathering state by watching for `icegatheringstatechange` events:

```js
pc.addEventListener("icegatheringstatechange", (ev) => {
  switch (pc.iceGatheringState) {
    case "new":
      /\* gathering is either just starting or has been reset \*/
      break;
    case "gathering":
      /\* gathering has begun or is ongoing \*/
      break;
    case "complete":
      /\* gathering has ended \*/
      break;
  }
});
```

As you can see in this example, the `icegatheringstatechange` event lets you know when the value of the `RTCPeerConnection` property `iceGatheringState` has been updated. If that value is now `complete`, you know that ICE gathering has just ended.

This is a more reliable approach than looking at the individual ICE messages for one indicating that the ICE session is finished.

Examples
--------

This example creates a simple handler for the `icecandidate` event that uses a function called `sendMessage()` to create and send a reply to the remote peer through the signaling server.

First, an example using `addEventListener()`:

```js
pc.addEventListener(
  "icecandidate",
  (ev) => {
    if (ev.candidate !== null) {
      sendMessage({
        type: "new-ice-candidate",
        candidate: ev.candidate,
      });
    }
  },
  false,
);
```

You can also set the `onicecandidate` event handler property directly:

```js
pc.onicecandidate = (ev) => {
  if (ev.candidate !== null) {
    sendMessage({
      type: "new-ice-candidate",
      candidate: ev.candidate,
    });
  }
};
```

Specifications
--------------

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-rtcpeerconnection-onicecandidate |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebRTC API
* Signaling and video calling


RTCPeerConnection: setConfiguration() method - Web APIs

RTCPeerConnection: setConfiguration() method
============================================

 The **`RTCPeerConnection.setConfiguration()`** method sets the
 current configuration of the `RTCPeerConnection` based on the values
 included in the specified object. This lets you change
 the ICE servers used by the connection and which transport policies to use.

 The most common use case for this method (and even then, probably not a very common use
 case) is to replace the set of ICE servers to be used. Two potential scenarios in which
 this might be done:

* The `RTCPeerConnection` was instantiated without specifying any ICE
 servers. If, for example, the `RTCPeerConnection()` constructor was called with no parameters, you would have to
 then call `setConfiguration()` to add ICE servers before ICE negotiation could begin.
* Renegotiation of the connection is needed, and a different set of ICE servers needs
 to be used for some reason. Perhaps the user has moved into a new region, so using new
 regional ICE servers is necessary, for example.
 In this situation, one might call `setConfiguration()` to switch to new regional ICE servers, then initiate an ICE restart.

**Note:** You cannot change the identity information for a connection once it's already been set.

Syntax
------

```js
setConfiguration(configuration)
```

### Parameters

`configuration`

 An object which provides the options to be set.
 The changes are not additive; instead, the new values completely replace the existing ones.
 See `RTCPeerConnection()` for more information on what options are allowed.

### Exceptions

`InvalidAccessError` `DOMException`

 Thrown if one or more of the URLs specified in `configuration.iceServers` is a TURN server, but complete login information is not provided (that is,
 either the `username` or `credential` is missing, or if `credentialType` is `"password"` and `credential` is not a string).
 This prevents successful login to the server.

`InvalidModificationError` `DOMException`

 Thrown if the `configuration` includes changed identity information, but the connection already has identity information specified.
 This happens if `configuration.peerIdentity` or `configuration.certificates` are set and their values differ from the current configuration.
 This may also be thrown if there are changes to `configuration.bundlePolicy` or `configuration.rtcpMuxPolicy`, or to `configuration.iceCandidatePoolSize` when `RTCPeerConnection.setLocalDescription()` has already been called.

`InvalidStateError` `DOMException`

Thrown if the `RTCPeerConnection` is closed.

`SyntaxError` `DOMException`

Thrown if the `configuration.iceServers` contains no URLs or if one of the values in the list is invalid.

`NotSupportedError` `DOMException`

Thrown if `configuration.iceServers` contains a URL with a scheme that is not supported.

Example
-------

In this example, it has already been determined that ICE restart is needed, and that negotiation needs to be done using a different ICE server.

```js
const restartConfig = {
  iceServers: [
    {
      urls: "turn:asia.myturnserver.net",
      username: "allie@oopcode.com",
      credential: "topsecretpassword",
    },
  ],
};

myPeerConnection.setConfiguration(restartConfig);

myPeerConnection
  .createOffer({ iceRestart: true })
  .then((offer) => myPeerConnection.setLocalDescription(offer))
  .then(() => {
    // send the offer to the other peer using the signaling server
  })
  .catch(reportError);
```

 First, a new object is created, `restartConfig`,
 specifying the new ICE server and its credentials. This is then passed into
 `setConfiguration()`. ICE negotiation is restarted by calling
 `createOffer()`, specifying
 `true` as the value of the `iceRestart` option. From there, we
 handle the process as usual, by setting the local description to the returned offer and
 then sending that offer to the other peer.

Specifications
--------------

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-rtcpeerconnection-setconfiguration |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `RTCPeerConnection.getConfiguration()`
* `RTCPeerConnection()`
* `RTCPeerConnection`


RTCPeerConnection: createDataChannel() method - Web APIs

RTCPeerConnection: createDataChannel() method
=============================================

 The **`createDataChannel()`** method
 on the `RTCPeerConnection` interface
 creates a new channel linked with the remote peer,
 over which any kind of data may be transmitted.
 This can be useful for back-channel content,
 such as images, file transfer, text chat, game update
 packets, and so forth.

 If the new data channel is the first one added to the connection, renegotiation is
 started by delivering a `negotiationneeded` event.

Syntax
------

```js
createDataChannel(label)
createDataChannel(label, options)
```

### Parameters

`label`

 A human-readable name for the channel.
 This string may not be longer than 65,535 bytes.

`options` Optional

 An object providing configuration options for the data channel.
 It can contain the following fields:

`ordered` Optional

 Indicates whether or not
 messages sent on the `RTCDataChannel`
 are required to arrive at their destination in the same order
 in which they were sent (`true`),
 or if they're allowed to arrive out-of-order (`false`).
 **Default: `true`.**

`maxPacketLifeTime` Optional

 The maximum number of milliseconds
 that attempts to transfer a message may take in unreliable mode.
 While this value is a 16-bit unsigned number,
 each user agent may clamp it
 to whatever maximum it deems appropriate.
 **Default: `null`.**

`maxRetransmits` Optional

 The maximum number of times
 the user agent should attempt to retransmit a message
 which fails the first time in unreliable mode.
 While this value is a 16-bit unsigned number,
 each user agent may clamp it to whatever maximum it deems appropriate.
 **Default: `null`.**

`protocol` Optional

 The name of the sub-protocol
 being used on the `RTCDataChannel`,
 if any;
 otherwise, the empty string (`""`).
 **Default: empty string (`""`).**
 This string may not be longer than 65,535 *bytes*.

`negotiated` Optional

 By default (`false`),
 data channels are negotiated in-band,
 where one side calls `createDataChannel`, and
 the other side listens to the `RTCDataChannelEvent` event
 using the `ondatachannel` event handler.
 Alternatively (`true`),
 they can be negotiated out of-band,
 where both sides call `createDataChannel`
 with an agreed-upon ID.
 **Default: `false`.**

`id` Optional

 A 16-bit numeric ID for the channel;
 permitted values are 0 to 65534.
 If you don't include this option,
 the user agent will select an ID for you.

**Note:** These options represent the script-settable subset of the properties on the
 `RTCDataChannel` interface.

### Return value

 A new `RTCDataChannel` object with the specified `label`,
 configured using the options specified by `options` if that parameter is
 included; otherwise, the defaults listed above are established.

### Exceptions

`InvalidStateError` `DOMException`

Thrown if the `RTCPeerConnection` is closed.

`TypeError`

Thrown in the following situations:

* The label and/or protocol string is too long; these cannot be longer than 65,535
 bytes (bytes, rather than characters).
* The `id` is 65535. While this is a valid unsigned 16-bit value, it's
 not a permitted value for `id`.

`SyntaxError` `DOMException`

 Thrown if values were specified for both the `maxPacketLifeTime` and
 `maxRetransmits` options. You may specify a non-`null`
 value for only one of these.

`ResourceInUse` `DOMException`

 Thrown if an `id` was specified, but another `RTCDataChannel` is
 already using the same value.

`OperationError` `DOMException`

 Thrown if either the specified `id` is already in use, or if no `id` was
 specified, the WebRTC layer was unable to automatically generate an ID because all IDs
 are in use.

Examples
--------

 This example shows how to create a data channel and set up handlers for the
 `open` and `message` events to send and receive messages on it
 (For brevity, the example assumes onnegotiationneeded is set up).

```js
// Offerer side

const pc = new RTCPeerConnection(options);
const channel = pc.createDataChannel("chat");
channel.onopen = (event) => {
  channel.send("Hi you!");
};
channel.onmessage = (event) => {
  console.log(event.data);
};
```

```js
// Answerer side

const pc = new RTCPeerConnection(options);
pc.ondatachannel = (event) => {
  const channel = event.channel;
  channel.onopen = (event) => {
    channel.send("Hi back!");
  };
  channel.onmessage = (event) => {
    console.log(event.data);
  };
};
```

 Alternatively, more symmetrical out-of-band negotiation can be used, using an
 agreed-upon id (0 here):

```js
// Both sides

const pc = new RTCPeerConnection(options);
const channel = pc.createDataChannel("chat", { negotiated: true, id: 0 });
channel.onopen = (event) => {
  channel.send("Hi!");
};
channel.onmessage = (event) => {
  console.log(event.data);
};
```

 For a more thorough example showing how the connection and channel are established, see
 A simple RTCDataChannel sample.

Specifications
--------------

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-peerconnection-createdatachannel |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `RTCDataChannel`
* A simple RTCDataChannel sample
* `RTCPeerConnection`


RTCPeerConnection: remoteDescription property - Web APIs

RTCPeerConnection: remoteDescription property
=============================================

 The read-only property
 **`RTCPeerConnection.remoteDescription`** returns a
 `RTCSessionDescription` describing the session (which includes
 configuration and media information) for the remote end of the connection. If this
 hasn't been set yet, this is `null`.

 The returned value typically reflects a remote description which has been received over
 the signaling server (as either an offer or an answer) and then put into effect by your
 code calling `RTCPeerConnection.setRemoteDescription()` in response.

Syntax
------

```js
const sessionDescription = peerConnection.remoteDescription
```

 On a more fundamental level, the returned value is the value of
 `RTCPeerConnection.pendingRemoteDescription` if that property isn't
 `null`; otherwise, the value of
 `RTCPeerConnection.currentRemoteDescription` is returned. See
 Pending and current descriptions in the WebRTC Connectivity page for details on this algorithm and why it's used.

Example
-------

 This example looks at the `remoteDescription` and displays an alert
 containing the `RTCSessionDescription` object's `type` and
 `sdp` fields.

```js
const pc = new RTCPeerConnection();
// ...
const sd = pc.remoteDescription;
if (sd) {
  alert(`Remote session: type='${sd.type}'; sdp description='${sd.sdp}'`);
} else {
  alert("No remote session yet.");
}
```

Specifications
--------------

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-peerconnection-remotedescription |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `RTCPeerConnection.setRemoteDescription()`,
 `RTCPeerConnection.pendingRemoteDescription`,
 `RTCPeerConnection.currentRemoteDescription`
* `RTCPeerConnection.setLocalDescription()`,
 `RTCPeerConnection.pendingLocalDescription`,
 `RTCPeerConnection.currentLocalDescription`,
 `RTCPeerConnection.localDescription`
* WebRTC


RTCPeerConnection: restartIce() method - Web APIs

RTCPeerConnection: restartIce() method
======================================

 The WebRTC API's
 `RTCPeerConnection` interface offers the
 **`restartIce()`** method to allow a web application to easily
 request that ICE candidate gathering be redone on both ends of the
 connection.
 This simplifies the process by allowing the same method to be used
 by either the caller or the receiver to trigger an ICE restart.

 After `restartIce()` returns, the offer returned by the next call to
 `createOffer()` is automatically
 configured to trigger ICE restart on both the local peer (once the local peer has been
 set) and on the remote peer, once the offer is sent across your signaling mechanism and
 the remote peer has set its description as well.

`restartIce()` causes the
 `negotiationneeded` event to
 be fired on the `RTCPeerConnection` to inform the application that it should
 perform negotiation using its signaling channel.

 If negotiation fails to complete—either due to rollback or because incoming offers are
 in the process of being negotiated—the `RTCPeerConnection` will remember
 that you requested ICE restart. The next time the connection's
 `signalingState` changes to
 `stable`, the connection will fire the
 `negotiationneeded` event.
 This process continues until an ICE restart has been successfully completed.

Syntax
------

```js
restartIce()
```

### Parameters

None.

### Return value

None (`undefined`).

Usage notes
-----------

 After calling `restartIce()`, the next offer created using
 `createOffer()` will initiate ICE restart
 once sent to the remote peer over your signaling mechanism. Restarting ICE essentially
 resets ICE so that it creates all new candidates using new credentials. Existing media
 transmissions continue uninterrupted during this process.

 For details about how ICE restart works, see
 ICE restart and
 RFC 5245, section 9.1.1.1: ICE specification.

Examples
--------

 This example creates a handler for the
 `iceconnectionstatechange` event that handles a transition to the `failed`
 state by restarting ICE in order to try again.

```js
pc.addEventListener("iceconnectionstatechange", (event) => {
  if (pc.iceConnectionState === "failed") {
    /\* possibly reconfigure the connection in some way here \*/
    /\* then request ICE restart \*/
    pc.restartIce();
  }
});
```

 With this code in place, a transition to the `failed` state during ICE
 negotiation will cause a `negotiationneeded` event to be fired, in response to which your code should
 renegotiate as usual. However, because you have called `restartIce()`, your
 call to `createOffer()` which occurs in
 the handler for `negotiationneeded` will trigger an ICE restart rather than
 just a regular renegotiation.

Specifications
--------------

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-rtcpeerconnection-restartice |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebRTC API
* Lifetime of a WebRTC session
* Signaling and video calling


RTCPeerConnection: iceConnectionState property - Web APIs

RTCPeerConnection: iceConnectionState property
==============================================

 The read-only property **`RTCPeerConnection.iceConnectionState`** returns
 a string which state of the ICE agent associated with the `RTCPeerConnection`:
 `new`, `checking`, `connected`, `completed`,
 `failed`, `disconnected`, and `closed`.

 It describes the current state of the ICE agent
 and its connection to the ICE server;
 that is, the STUN or TURN server.

 You can detect when this value has changed by watching for the
 `iceconnectionstatechange` event.

Value
-----

The current state of the ICE agent and its connection. The value is one of the following strings:

`new`

 The ICE agent is gathering addresses
 or is waiting to be given remote candidates
 through calls to `RTCPeerConnection.addIceCandidate()` (or both).

`checking`

 The ICE agent has been given one or more remote candidates
 and is checking pairs of local and remote candidates against one another
 to try to find a compatible match,
 but has not yet found a pair which will allow the peer connection to be made.
 It is possible that gathering of candidates is also still underway.

`connected`

 A usable pairing of local and remote candidates has been found for all components of the connection,
 and the connection has been established.
 It is possible that gathering is still underway,
 and it is also possible that the ICE agent is still checking candidates
 against one another
 looking for a better connection to use.

`completed`

 The ICE agent has finished gathering candidates,
 has checked all pairs against one another,
 and has found a connection for all components.

`failed`

 The ICE candidate has checked all candidates pairs against one another
 and has failed to find compatible matches for all components of the connection.
 It is, however, possible that the ICE agent did find compatible connections for some components.

`disconnected`

 Checks to ensure
 that components are still connected failed
 for at least one component of the `RTCPeerConnection`.
 This is a less stringent test than `failed`
 and may trigger intermittently
 and resolve just as spontaneously on less reliable networks,
 or during temporary disconnections.
 When the problem resolves,
 the connection may return to the `connected` state.

`closed`

 The ICE agent for this `RTCPeerConnection` has shut down
 and is no longer handling requests.

Examples
--------

```js
const pc = new RTCPeerConnection();
const state = pc.iceConnectionState;
```

Specifications
--------------

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-peerconnection-ice-connection-state |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebRTC API
* `iceconnectionstatechange`
* `RTCPeerConnection`


RTCPeerConnection: currentRemoteDescription property - Web APIs

RTCPeerConnection: currentRemoteDescription property
====================================================

 The read-only property
 **`RTCPeerConnection.currentRemoteDescription`** returns an
 `RTCSessionDescription` object describing the remote end of the connection
 as it was most recently successfully negotiated since the last time the
 `RTCPeerConnection` finished negotiating and connecting to a remote peer.
 Also included is a list of any ICE candidates that may already have been generated by
 the ICE agent since the offer or answer represented by the description was first
 instantiated.

 To change the `currentRemoteDescription`, call
 `RTCPeerConnection.setRemoteDescription()`, which triggers a series of
 events which leads to this value being set. For details on what exactly happens and why
 the change isn't necessarily instantaneous, see
 Pending and current descriptions in the WebRTC Connectivity page.

**Note:** Unlike `RTCPeerConnection.remoteDescription`, this value represents the
 actual current state of the local end of the connection;
 `remoteDescription` may specify a description which the connection is
 currently in the process of switching over to.

Value
-----

 The current description of the remote end of the connection, if one has been set. If
 none has been successfully set, this value is `null`.

Examples
--------

 This example looks at the `currentRemoteDescription` and displays an alert
 containing the `RTCSessionDescription` object's `type` and
 `sdp` fields.

```js
const pc = new RTCPeerConnection();
// ...
const sd = pc.currentRemoteDescription;
if (sd) {
  alert(`Local session: type='${sd.type}'; sdp description='${sd.sdp}'`);
} else {
  alert("No local session yet.");
}
```

Specifications
--------------

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-peerconnection-currentremotedesc |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `RTCPeerConnection.setRemoteDescription()`,
 `RTCPeerConnection.pendingRemoteDescription`,
 `RTCPeerConnection.remoteDescription`
* `RTCPeerConnection.setRemoteDescription()`,
 `RTCPeerConnection.remoteDescription`,
 `RTCPeerConnection.pendingRemoteDescription`,
 `RTCPeerConnection.currentRemoteDescription`
* WebRTC


RTCPeerConnection: canTrickleIceCandidates property - Web APIs

RTCPeerConnection: canTrickleIceCandidates property
===================================================

 The read-only **`RTCPeerConnection`** property **`canTrickleIceCandidates`**
 returns a boolean value which indicates whether or not the remote peer can accept
 trickled ICE candidates.

**ICE trickling** is the process of continuing to send candidates after
 the initial offer or answer has already been sent to the other peer.

 This property is only set after having called
 `RTCPeerConnection.setRemoteDescription()`. Ideally, your signaling
 protocol provides a way to detect trickling support, so that you don't need to rely on
 this property. A WebRTC browser will always support trickle ICE. If trickling isn't
 supported, or you aren't able to tell, you can check for a falsy value for this
 property and then wait until the value of
 `iceGatheringState` changes to
 `"completed"` before creating and sending the initial offer. That way, the
 offer contains all of the candidates.

Value
-----

 A boolean value that is `true` if the remote peer can accept
 trickled ICE candidates and `false` if it cannot. If no remote peer has
 been established, this value is `null`.

**Note:** This property's value is determined once the local peer has
 called `RTCPeerConnection.setRemoteDescription()`; the provided
 description is used by the ICE agent to determine whether or not the remote peer
 supports trickled ICE candidates.

Examples
--------

```js
const pc = new RTCPeerConnection();

function waitToCompleteIceGathering(pc) {
  return new Promise((resolve) => {
    pc.addEventListener(
      "icegatheringstatechange",
      (e) =>
        e.target.iceGatheringState === "complete" &&
        resolve(pc.localDescription),
    );
  });
}

// The following code might be used to handle an offer from a peer when
// it isn't known whether it supports trickle ICE.
async function newPeer(remoteOffer) {
  await pc.setRemoteDescription(remoteOffer);
  const offer = await pc.createOffer();
  await pc.setLocalDescription(offer);
  if (pc.canTrickleIceCandidates) return pc.localDescription;
  const answer = await waitToCompleteIceGathering(pc);
  sendAnswerToPeer(answer); //To peer via signaling channel
}
// Handle error with try/catch

pc.addEventListener(
  "icecandidate",
  (e) => pc.canTrickleIceCandidates && sendCandidateToPeer(e.candidate),
);
```

Specifications
--------------

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-rtcpeerconnection-cantrickleicecandidates |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebRTC
* `RTCPeerConnection.addIceCandidate()`
* Lifetime of a WebRTC session


RTCPeerConnection: generateCertificate() static method - Web APIs

RTCPeerConnection: generateCertificate() static method
======================================================

 The static **`RTCPeerConnection.generateCertificate()`**
 function creates an X.509 certificate and corresponding private key, returning a promise
 that resolves with the new `RTCCertificate` once it's generated.

Syntax
------

```js
RTCPeerConnection.generateCertificate(keygenAlgorithm)
```

### Parameters

`keygenAlgorithm`

 A Web Crypto API
`AlgorithmIdentifier` string or an `Algorithm` -subclassed
 object specifying an algorithm to use when creating the certificate's key.

**Note:** `RTCPeerConnection.generateCertificate()` is a static method, so it is
 always called on the `RTCPeerConnection` interface itself, not an instance
 thereof.

### Return value

 A promise which resolves to a new `RTCCertificate` object containing a new
 key based on the specified options.

### Exceptions

`NotSupportedError` `DOMException`

 Thrown if the normalized form of `keygenAlgorithm` specifies an algorithm or
 algorithm settings that the browser doesn't support, or which it does not allow for
 use with an `RTCPeerConnection`.

 Other errors may occur; for example, if the specified `keygenAlgorithm`
 can't be successfully converted into an `RTCCertificateExpiration`
 dictionary, the error that occurs during that conversion will be thrown.

Description
-----------

 If a string is specified, it must be a Web Crypto API-compatible algorithm name string. Alternatively, you can provide
 specific details for the algorithm's configuration by providing an object based on one
 of the Web Crypto API's `Algorithm` class's subclasses.

### Standard configurations

 All browsers are required to support the following two configurations. It's entirely
 possible that a browser's *default* settings may be different, but these are
 always supported.

#### RSASSA-PKCS1-v1\_5

```js
let stdRSACertificate = {
  name: "RSASSA-PKCS1-v1\_5",
  modulusLength: 2048,
  publicExponent: new Uint8Array([1, 0, 1]),
  hash: "SHA-256",
};
```

#### ECDSA

```js
let stdECDSACertificate = {
  name: "ECDSA",
  namedCurve: "P-256",
};
```

### Certificate expiration time

 By default the new certificate is configured with `expires` set to a value of 2592000000 milliseconds, or 30 days.
 The expiration time cannot exceed 31536000000 milliseconds, or 365 days.
 It's also useful to note that browsers may further restrict the expiration time of certificates if they choose.

Examples
--------

### Specifying algorithm details

 This example requests a new RSASSA-PKCS1-v1\_5 certificate using a SHA-256 hash and a
 modulus length of 2048.

```js
RTCPeerConnection.generateCertificate({
  name: "RSASSA-PKCS1-v1\_5",
  hash: "SHA-256",
  modulusLength: 2048,
  publicExponent: new Uint8Array([1, 0, 1]),
}).then((cert) => {
  const pc = new RTCPeerConnection({ certificates: [cert] });
});
```

### Specifying an algorithm by name

 The example below specifies a string requesting an ECDSA
 certificate.

```js
RTCPeerConnection.generateCertificate("ECDSA");
```

Specifications
--------------

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-rtcpeerconnection-generatecertificate |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebRTC API
* Web Crypto API
* Website security
* Web security
* Symmetric-key cryptography
* `crypto`


RTCPeerConnection: icegatheringstatechange event - Web APIs

RTCPeerConnection: icegatheringstatechange event
================================================

 The **`icegatheringstatechange`** event is sent to the `onicegatheringstatechange` event handler on an `RTCPeerConnection` when the state of the ICE candidate gathering process changes.
 This signifies that the value of the connection's `iceGatheringState` property has changed.

When ICE first starts to gather connection candidates, the value changes from `new` to `gathering` to indicate that the process of collecting candidate configurations for the connection has begun. When the value changes to `complete`, all of the transports that make up the `RTCPeerConnection` have finished gathering ICE candidates.

**Note:** While you can determine that ICE candidate gathering is complete by watching for `icegatheringstatechange` events and checking for the value of `iceGatheringState` to become `complete`, you can also have your handler for the `icecandidate` event look to see if its `candidate` property is `null`. This also indicates that collection of candidates is finished.

This event is not cancelable and does not bubble.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("icegatheringstatechange", (event) => {});

onicegatheringstatechange = (event) => {};
```

Event type
----------

A generic `Event`.

Examples
--------

This example creates a handler for `icegatheringstatechange` events.

```js
pc.onicegatheringstatechange = (ev) => {
  let connection = ev.target;

  switch (connection.iceGatheringState) {
    case "gathering":
      /\* collection of candidates has begun \*/
      break;
    case "complete":
      /\* collection of candidates is finished \*/
      break;
  }
};
```

Likewise, you can use `addEventListener()` to add a listener for `icegatheringstatechange` events:

```js
pc.addEventListener(
  "icegatheringstatechange",
  (ev) => {
    let connection = ev.target;

    switch (connection.iceGatheringState) {
      case "gathering":
        // collection of candidates has begun
        break;
      case "complete":
        // collection of candidates is finished
        break;
    }
  },
  false,
);
```

Specifications
--------------

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-rtcpeerconnection-onicegatheringstatechange |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebRTC API
* Signaling and video calling
* WebRTC connectivity
* Lifetime of a WebRTC session


RTCPeerConnection: pendingRemoteDescription property - Web APIs

RTCPeerConnection: pendingRemoteDescription property
====================================================

 The read-only property
 **`RTCPeerConnection.pendingRemoteDescription`** returns an
 `RTCSessionDescription` object describing a pending configuration change
 for the remote end of the connection. This does not describe the connection as it
 currently stands, but as it may exist in the near future. Use
 `RTCPeerConnection.currentRemoteDescription` or
 `RTCPeerConnection.remoteDescription` to get the current session
 description for the remote endpoint. For details on the difference, see
 Pending and current descriptions in the WebRTC Connectivity page.

Value
-----

 If a remote description change is in progress, this is an
 `RTCSessionDescription` describing the proposed configuration. Otherwise,
 this returns `null`.

Examples
--------

 This example looks at the `pendingRemoteDescription` to determine whether or
 not there's a description change being processed.

```js
const pc = new RTCPeerConnection();
// ...
const sd = pc.pendingRemoteDescription;
if (sd) {
  // There's a description change underway!
} else {
  // No description change pending
}
```

Specifications
--------------

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-peerconnection-pendingremotedesc |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

**Note:** The addition of `pendingRemoteDescription` and
 `currentRemoteDescription`
 to the WebRTC spec is relatively recent. In browsers which don't support them, only
 `remoteDescription` is available.

See also
--------

* `RTCPeerConnection.setRemoteDescription()`,
 `RTCPeerConnection.currentRemoteDescription`,
 `RTCPeerConnection.remoteDescription`
* `RTCPeerConnection.setLocalDescription()`,
 `RTCPeerConnection.localDescription`,
 `RTCPeerConnection.pendingLocalDescription`,
 `RTCPeerConnection.currentLocalDescription`
* WebRTC


RTCPeerConnection: addstream event - Web APIs

RTCPeerConnection: addstream event
==================================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

The obsolete **`addstream`** event is sent to an `RTCPeerConnection` when new media, in the form of a `MediaStream` object, has been added to it.

**Warning:** This event has been removed from the WebRTC specification. You should instead watch for the `track` event, which is sent for each media track added to the `RTCPeerConnection`.

You can, similarly, watch for streams to be removed from the connection by monitoring the `removestream` event.

This event is not cancelable and does not bubble.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("addstream", (event) => {});

onaddstream = (event) => {};
```

Event type
----------

A `MediaStreamEvent`. Inherits from `Event`.

Event properties
----------------

*A `MediaStreamEvent` being an `Event`, this event also implements these properties*.

`MediaStreamEvent.stream` Read only

Contains the `MediaStream` containing the stream associated with the event.

Examples
--------

This example looks to determine if the user's browser supports the `track` event. If it does, a `track` event listener is set up; otherwise, an `addstream` event listener is set up. `pc` is an `RTCPeerConnection`.

```js
if (pc.addTrack !== undefined) {
  pc.ontrack = (ev) => {
    ev.streams.forEach((stream) => doAddStream(stream));
  };
} else {
  pc.onaddstream = (ev) => {
    doAddStream(ev.stream);
  };
}
```

This calls a function `doAddStream()` once for each stream being added to the `RTCPeerConnection`, regardless of whether the browser sends `addstream` or `track`.

You can also use the `addEventListener()` method to set an event listener:

```js
pc.addEventListener("addstream", (ev) => doAddStream(ev.stream), false);
```

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebRTC API
* `RTCPeerConnection.addStream()`
* `MediaStreamEvent`


RTCPeerConnection: negotiationneeded event - Web APIs

RTCPeerConnection: negotiationneeded event
==========================================

 A **`negotiationneeded`** event is sent to the `RTCPeerConnection` when negotiation of the connection through the signaling channel is required.
 This occurs both during the initial setup of the connection as well as any time a change to the communication environment requires reconfiguring the connection.

The `negotiationneeded` event is first dispatched to the `RTCPeerConnection` when media is first added to the connection. This starts the process of ICE negotiation by instructing your code to begin exchanging ICE candidates through the signaling server. See Signaling transaction flow for a description of the signaling process that begins with a `negotiationneeded` event.

This event is not cancelable and does not bubble.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("negotiationneeded", (event) => {});

onnegotiationneeded = (event) => {};
```

Event type
----------

A generic `Event`.

Examples
--------

In this example, we use `addEventListener()` to create an event handler for `negotiationneeded`. Its role is to create an SDP offer and send it through the signaling channel to the remote peer.

```js
pc.addEventListener(
  "negotiationneeded",
  (ev) => {
    pc.createOffer()
      .then((offer) => pc.setLocalDescription(offer))
      .then(() =>
        sendSignalingMessage({
          type: "video-offer",
          sdp: pc.localDescription,
        }),
      )
      .catch((err) => {
        // handle error
      });
  },
  false,
);
```

After creating the offer, the local end is configured by calling `RTCPeerConnection.setLocalDescription()`; then a signaling message is created and sent to the remote peer through the signaling server, to share that offer with the other peer. The other peer should recognize this message and follow up by creating its own `RTCPeerConnection`, setting the remote description with `setRemoteDescription()`, and then creating an answer to send back to the offering peer.

You can also set an event handler for the `negotiationneeded` event by assigning the event handler function to the `onnegotiationneeded` property:

```js
pc.onnegotiationneeded = (ev) => {
  pc.createOffer()
    .then((offer) => pc.setLocalDescription(offer))
    .then(() =>
      sendSignalingMessage({
        type: "video-offer",
        sdp: pc.localDescription,
      }),
    )
    .catch((err) => {
      // handle error
    });
};
```

For a more detailed example, see Starting negotiation.

Specifications
--------------

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-rtcpeerconnection-onnegotiationneeded |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebRTC API
* Signaling and video calling
* Lifetime of a WebRTC session
* WebRTC connectivity
* Introduction to WebRTC protocols


RTCPeerConnection: signalingstatechange event - Web APIs

RTCPeerConnection: signalingstatechange event
=============================================

A **`signalingstatechange`** event is sent to an `RTCPeerConnection` to notify it that its signaling state, as indicated by the `signalingState` property, has changed.

This event is not cancelable and does not bubble.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("signalingstatechange", (event) => {});

onsignalingstatechange = (event) => {};
```

Event type
----------

A generic `Event`.

Examples
--------

Given an `RTCPeerConnection`, `pc`, and an `updateStatus()` function that presents status information to the user, this code sets up an event handler to let the user know when the ICE negotiation process finishes up.

```js
pc.addEventListener(
  "signalingstatechange",
  (ev) => {
    switch (pc.signalingState) {
      case "stable":
        updateStatus("ICE negotiation complete");
        break;
    }
  },
  false,
);
```

Using `onsignalingstatechange`, it looks like this:

```js
pc.onsignalingstatechange = (ev) => {
  switch (pc.signalingState) {
    case "stable":
      updateStatus("ICE negotiation complete");
      break;
  }
};
```

Specifications
--------------

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # event-signalingstatechange |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebRTC API
* `RTCPeerConnection.signalingState`


RTCPeerConnection: removestream event - Web APIs

RTCPeerConnection: removestream event
=====================================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

 The obsolete **`removestream`** event was sent to an `RTCPeerConnection` to inform it that a `MediaStream` had been removed from the connection.
 You can use the `RTCPeerConnection` interface's `onremovestream` property to set a handler for this event.

This is the counterpart to the `addstream` event, which is also obsolete.

**Warning:** This event has been removed from the WebRTC specification in favor of the existing `removetrack` event on the remote `MediaStream` and the corresponding event handler property of the remote `MediaStream`. The `RTCPeerConnection` API is now track-based, so having zero tracks in the remote stream is equivalent to the remote stream being removed, which caused a `removestream` event.

This event is not cancelable and does not bubble.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("removestream", (event) => {});

onremovestream = (event) => {};
```

Event type
----------

A `MediaStreamEvent`. Inherits from `Event`.

Event properties
----------------

*A `MediaStreamEvent` being an `Event`, this event also implements these properties*.

`MediaStreamEvent.stream` Read only

Contains the `MediaStream` containing the stream associated with the event.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebRTC API
* `RTCPeerConnection.removeStream()`
* `removetrack`


RTCPeerConnection: connectionstatechange event - Web APIs

RTCPeerConnection: connectionstatechange event
==============================================

 The **`connectionstatechange`** event is sent to the `onconnectionstatechange` event handler on an `RTCPeerConnection` object after a new track has been added to an `RTCRtpReceiver` which is part of the connection.
 The new connection state can be found in `connectionState`, and is one of the string values: `new`, `connecting`, `connected`, `disconnected`, `failed`, or `closed`.

This event is not cancelable and does not bubble.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("connectionstatechange", (event) => {});

onconnectionstatechange = (event) => {};
```

Event type
----------

A generic `Event`.

Examples
--------

 For an `RTCPeerConnection` named `peerConnection`, this example uses `addEventListener()` to handle changes to the connectivity of the WebRTC session.
 It calls an app-defined function called `setOnlineStatus()` to update a status display.

```js
peerConnection.addEventListener(
  "connectionstatechange",
  (event) => {
    switch (peerConnection.connectionState) {
      case "new":
      case "connecting":
        setOnlineStatus("Connecting…");
        break;
      case "connected":
        setOnlineStatus("Online");
        break;
      case "disconnected":
        setOnlineStatus("Disconnecting…");
        break;
      case "closed":
        setOnlineStatus("Offline");
        break;
      case "failed":
        setOnlineStatus("Error");
        break;
      default:
        setOnlineStatus("Unknown");
        break;
    }
  },
  false,
);
```

You can also create a handler for the `connectionstatechange` event using the `RTCPeerConnection.onconnectionstatechange` property:

```js
peerConnection.onconnectionstatechange = (ev) => {
  switch (peerConnection.connectionState) {
    case "new":
    case "connecting":
      setOnlineStatus("Connecting…");
      break;
    // …
    default:
      setOnlineStatus("Unknown");
      break;
  }
};
```

Specifications
--------------

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-rtcpeerconnection-onconnectionstatechange |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebRTC API
* WebRTC connectivity
* Lifetime of a WebRTC session
* `RTCPeerConnection.connectionState`


RTCPeerConnection: datachannel event - Web APIs

RTCPeerConnection: datachannel event
====================================

A **`datachannel`** event is sent to an `RTCPeerConnection` instance when an `RTCDataChannel` has been added to the connection, as a result of the remote peer calling `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.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("datachannel", (event) => {});

ondatachannel = (event) => {};
```

Event type
----------

An `RTCDataChannelEvent`. Inherits from `Event`.

Event

RTCDataChannelEventEvent properties
----------------

*Also inherits properties from `Event`.*

`channel` Read only

Returns the `RTCDataChannel` associated with the event.

Examples
--------

This example sets up a function that handles `datachannel` events by gathering the information needed to communicate with the newly added `RTCDataChannel` and by adding event handlers for the events that occur on that channel.

```js
pc.addEventListener(
  "datachannel",
  (ev) => {
    receiveChannel = ev.channel;
    receiveChannel.onmessage = myHandleMessage;
    receiveChannel.onopen = myHandleOpen;
    receiveChannel.onclose = myHandleClose;
  },
  false,
);
```

`receiveChannel` is set to the value of the event's `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 `RTCPeerConnection` interface's `ondatachannel` event handler property, like this:

```js
pc.ondatachannel = (ev) => {
  receiveChannel = ev.channel;
  receiveChannel.onmessage = myHandleMessage;
  receiveChannel.onopen = myHandleOpen;
  receiveChannel.onclose = myHandleClose;
};
```

Specifications
--------------

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-rtcpeerconnection-ondatachannel |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebRTC API
* Using WebRTC data channels
* A simple RTCDataChannel sample
* `RTCDataChannelEvent`
* `RTCPeerConnection.createDataChannel()`


RTCPeerConnection: iceGatheringState property - Web APIs

RTCPeerConnection: iceGatheringState property
=============================================

 The read-only property **`RTCPeerConnection.iceGatheringState`** returns a string
 that describes the connection's ICE gathering state.
 This lets you detect, for example, when collection of ICE candidates has finished.

 You can detect when the value of this property changes by watching for an event of type
 `icegatheringstatechange`.

Value
-----

The possible values are:

`new`

The peer connection was just created and hasn't done any networking yet.

`gathering`

The ICE agent is in the process of gathering candidates for the connection.

`complete`

 The ICE agent has finished gathering candidates.
 If something happens that requires collecting new candidates,
 such as a new interface being added or the addition of a new ICE server,
 the state will revert to `gathering` to gather those candidates.

Example
-------

```js
const pc = new RTCPeerConnection();
const state = pc.iceGatheringState;
```

Specifications
--------------

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-peerconnection-ice-gathering-state |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `icegatheringstatechange`
* WebRTC


RTCPeerConnection: connectionState property - Web APIs

RTCPeerConnection: connectionState property
===========================================

The read-only **`connectionState`** property of the `RTCPeerConnection` interface indicates the current state of the peer connection by returning one of the following string values: `new`, `connecting`, `connected`, `disconnected`, `failed`, or `closed`.

This state essentially represents the aggregate state of all ICE transports (which are of type `RTCIceTransport` or `RTCDtlsTransport`) being used by the connection.

When this property's value changes, a `connectionstatechange` event is sent to the `RTCPeerConnection` instance.

Value
-----

 A string representing the current state of the connection.
 This can take on of the following values:

`new`

At least one of the connection's ICE transports (`RTCIceTransport` or `RTCDtlsTransport` objects) is in the `new` state, and none of them are in one of the following states: `connecting`, `checking`, `failed`, `disconnected`, or all of the connection's transports are in the `closed` state.

`connecting`

 One or more of the ICE transports are currently in the process of establishing a connection;
 that is, their `iceConnectionState` is either `checking` or `connected`, and no transports are in the `failed` state.

`connected`

 Every ICE transport used by the connection is either in use (state `connected` or `completed`) or is closed (state `closed`);
 in addition, at least one transport is either `connected` or `completed`.

`disconnected`

At least one of the ICE transports for the connection is in the `disconnected` state and none of the other transports are in the states: `failed`, `connecting`, or `checking`.

`failed`

One or more of the ICE transports on the connection is in the `failed` state.

`closed`

The `RTCPeerConnection` is closed.

Example
-------

```js
const peerConnection = new RTCPeerConnection(configuration);

// …

const connectionState = peerConnection.connectionState;
```

Specifications
--------------

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-peerconnection-connection-state |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Lifetime of a WebRTC session
* `RTCPeerConnection`
* `connectionstatechange`
* WebRTC


RTCPeerConnection: addIceCandidate() method - Web APIs

RTCPeerConnection: addIceCandidate() method
===========================================

 When a website or app using `RTCPeerConnection` receives a new ICE candidate from the remote peer over its signaling channel, it delivers the newly-received candidate to the browser's ICE agent by calling **`RTCPeerConnection.addIceCandidate()`**.
 This adds this new remote candidate to the `RTCPeerConnection`'s remote description, which describes the state of the remote end of the connection.

 If the `candidate` parameter is missing or a value of `null` is given when calling `addIceCandidate()`, the added ICE candidate is an "end-of-candidates" indicator.
 The same is the case if the value of the specified object's `candidate` is either missing or an empty string (`""`), it signals that all remote candidates have been delivered.

The end-of-candidates notification is transmitted to the remote peer using a candidate with an a-line value of `end-of-candidates`.

 During negotiation, your app will likely receive many candidates which you'll deliver to the ICE agent in this way, allowing it to build up a list of potential connection methods.
 This is covered in more detail in the articles WebRTC connectivity and
 Signaling and video calling.

Syntax
------

```js
addIceCandidate(candidate)

addIceCandidate(candidate, successCallback) // deprecated
addIceCandidate(candidate, successCallback, failureCallback) // deprecated
```

### Parameters

`candidate` Optional

An `RTCIceCandidate` object, or an object that has the following properties:

`candidate` Optional

 A string describing the properties of the candidate, taken directly from the SDP attribute `"candidate"`.
 The candidate string specifies the network connectivity information for the candidate.
 If the `candidate` is an empty string (`""`), the end of the candidate list has been reached; this candidate is known as the "end-of-candidates" marker.

 The syntax of the candidate string is described in RFC 5245, section 15.1.
 For an a-line (attribute line) that looks like this:

```

a=candidate:4234997325 1 udp 2043278322 192.0.2.172 44323 typ host
```

 the corresponding `candidate` string's value will be
 `"candidate:4234997325 1 udp 2043278322 192.0.2.172 44323 typ host"`.

 The user agent always prefers candidates with the highest `priority`, all else being equal.
 In the example above, the priority is `2043278322`. The attributes are all separated by a single space character, and are in a specific order.
 The complete list of attributes for this example candidate is:

* `foundation` = 4234997325
* `component` = `"rtp"` (the number 1 is encoded to this string; 2 becomes `"rtcp"`)
* `protocol` = `"udp"`
* `priority` = 2043278322
* `ip` = `"192.0.2.172"`
* `port` = 44323
* `type` = `"host"`

Additional information can be found in `RTCIceCandidate.candidate`.

**Note:** For backward compatibility with older versions of the WebRTC specification, the constructor also accepts this string directly as an argument.

`sdpMid` Optional

A string containing the identification tag of the media stream with which the candidate is associated, or `null` if there is no associated media stream. The default is `null`.

Additional information can be found in `RTCIceCandidate.sdpMid`.

`sdpMLineIndex` Optional

A number property containing the zero-based index of the m-line with which the candidate is associated, within the SDP of the media description, or `null` if no such associated exists. The default is `null`.

Additional information can be found in `RTCIceCandidate.sdpMLineIndex`.

`usernameFragment` Optional

 A string containing the username fragment (usually referred to in shorthand as "ufrag" or "ice-ufrag").
 This fragment, along with the ICE password ("ice-pwd"), uniquely identifies a single ongoing ICE interaction (including for any communication with the STUN server).

 The string is generated by WebRTC at the beginning of the session.
 It may be up to 256 characters long, and at least 24 bits must contain random data.
 It has no default value and is not present unless set explicitly.

Additional information can be found in `RTCIceCandidate.usernameFragment`.

The method will throw a `TypeError` exception if both `sdpMid` and `sdpMLineIndex` are `null`.

The contents of the object should be constructed from a message received over the signaling channel, describing a newly received ICE candidate that's ready to be delivered to the local ICE agent.

If no `candidate` object is specified, or its value is `null`, an end-of-candidates signal is sent to the remote peer using the `end-of-candidates` a-line, formatted like this:
```

a=end-of-candidates
```

### Deprecated parameters

 In older code and documentation, you may see a callback-based version of this function.
 This has been deprecated and its use is **strongly** discouraged. You
 should update any existing code to use the `Promise`-based version of
 `addIceCandidate()` instead. The parameters for the older form of
 `addIceCandidate()` are described below, to aid in updating existing code.

`successCallback`
Deprecated

 A function to be called when the ICE candidate has been successfully added. This
 function receives no input parameters and doesn't return a value.

`failureCallback`
Deprecated

 A function to be called if attempting to add the ICE candidate fails. Receives as
 input a `DOMException` object describing why failure occurred.

### Return value

 A `Promise` that is fulfilled when the candidate has been successfully
 added to the remote peer's description by the ICE agent. The promise does not receive any input parameters.

### Exceptions

 When an error occurs while attempting to add the ICE candidate, the
 `Promise` returned by this method is rejected, returning one of the errors
 below as the `name` attribute in the specified
 `DOMException` object passed to the rejection handler.

`TypeError`

 Returned if the specified candidate's `sdpMid` and
 `sdpMLineIndex` are both `null`.

`InvalidStateError` `DOMException`

 Returned if the `RTCPeerConnection` currently has no remote peer established
 (`remoteDescription` is `null`).

`OperationError` `DOMException`

Returned in one of the following situations:

* The value specified for `sdpMid` is
 non-`null` and doesn't match the media description ID of any
 media description included within the
 `remoteDescription`.
* The specified value of `sdpMLineIndex` is greater than or equal to the number of media
 descriptions included in the remote description.
* The specified `ufrag`
 doesn't match the `ufrag` field in any of the remote
 descriptions being considered.
* One or more of the values in the `candidate` string are invalid or could not be parsed.
* Attempting to add the candidate fails for any reason.

Examples
--------

 This code snippet shows how to signal ICE candidates across an arbitrary signaling
 channel.

```js
// This example assumes that the other peer is using a signaling channel as follows:
//
// pc.onicecandidate = (event) => {
// if (event.candidate) {
// signalingChannel.send(JSON.stringify({ice: event.candidate})); // "ice" is arbitrary
// } else {
// // All ICE candidates have been sent
// }
// }

signalingChannel.onmessage = (receivedString) => {
  const message = JSON.parse(receivedString);
  if (message.ice) {
    // A typical value of ice here might look something like this:
    //
    // {candidate: "candidate:0 1 UDP 2122154243 192.0.2.43 53421 typ host", sdpMid: "0", …}
    //
    // Pass the whole thing to addIceCandidate:

    pc.addIceCandidate(message.ice).catch((e) => {
      console.log(`Failure during addIceCandidate(): ${e.name}`);
    });
  } else {
    // handle other things you might be signaling, like sdp
  }
};
```

 The last candidate to be signaled this way by the remote peer will be a special
 candidate denoting end-of-candidates. Out of interest, end-of-candidates may be
 manually indicated as follows:

```js
pc.addIceCandidate({ candidate: "" });
```

 However, in most cases you won't need to look for this explicitly, since the events
 driving the `RTCPeerConnection` will deal with it for you, sending the
 appropriate events.

Specifications
--------------

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-peerconnection-addicecandidate |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebRTC API
* Signaling and video calling
* Introduction to WebRTC protocols
* WebRTC connectivity
* Lifetime of a WebRTC session


RTCPeerConnection: getStats() method - Web APIs

RTCPeerConnection: getStats() method
====================================

 The `RTCPeerConnection` method
 **`getStats()`** returns a promise which resolves with data
 providing statistics about either the overall connection or about the specified
 `MediaStreamTrack`.

Syntax
------

```js
getStats()
getStats(selector)

getStats(selector, successCallback, failureCallback) // deprecated
```

### Parameters

`selector` Optional

 A `MediaStreamTrack` for which to gather statistics. If this is
 `null` (the default value), statistics will be gathered for the entire
 `RTCPeerConnection`.

### Deprecated parameters

 In older code and documentation, you may see a callback-based version of this function.
 This has been deprecated and its use is **strongly** discouraged. You
 should update any existing code to use the `Promise`-based version of
 `getStats()` instead. The parameters for the older form of
 `getStats()` are described below, to aid in updating existing code.

`successCallback`
Deprecated

A callback function called once the report has been successfully generated.

`failureCallback`
Deprecated

A callback function called once the report has failed to be generated.

### Return value

 A `Promise` which resolves with an `RTCStatsReport` object
 providing connection statistics. The report's contents depend on the
 `selector` and other details of the connection.

### Exceptions

 This method does not throw exceptions; instead, it rejects the returned promise with
 one of the following errors:

`InvalidAccessError` `DOMException`

 Thrown when there is no `RTCRtpSender` or `RTCRtpReceiver` whose
 `track` matches the specified `selector`, or
 `selector` matches more than one sender or receiver.

Examples
--------

 This example creates a periodic function using
 `setInterval()` that collects
 statistics for an `RTCPeerConnection` every second, generating an
 HTML-formatted report and inserting it into a specific element in the DOM.

```js
setInterval(() => {
  myPeerConnection.getStats(null).then((stats) => {
    let statsOutput = "";

    stats.forEach((report) => {
      statsOutput +=
        `<h2>Report: ${report.type}</h2>\n<strong>ID:</strong> ${report.id}<br>\n` +
        `<strong>Timestamp:</strong> ${report.timestamp}<br>\n`;

      // Now the statistics for this report; we intentionally drop the ones we
      // sorted to the top above

      Object.keys(report).forEach((statName) => {
        if (
          statName !== "id" &&
          statName !== "timestamp" &&
          statName !== "type"
        ) {
          statsOutput += `<strong>${statName}:</strong> ${report[statName]}<br>\n`;
        }
      });
    });

    document.querySelector(".stats-box").innerHTML = statsOutput;
  });
}, 1000);
```

 This works by calling `getStats()`, then, when the promise is resolved,
 iterates over the `RTCStatsReport` objects on the returned
 `RTCStatsReport`. A section is created for each report with a header and
 all of the statistics below, with the type, ID, and timestamp handled specially to place
 them at the top of the list.

 Once the HTML for the report is generated, it is
 injected into the element whose class is `"stats-box"` by setting its
 `innerHTML` property.

Specifications
--------------

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # widl-RTCPeerConnection-getStats-Promise-RTCStatsReport--MediaStreamTrack-selector |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


RTCPeerConnection: iceconnectionstatechange event - Web APIs

RTCPeerConnection: iceconnectionstatechange event
=================================================

 An **`iceconnectionstatechange`** event is sent to an `RTCPeerConnection` object each time the ICE connection state changes during the negotiation process.
 The new ICE connection state is available in the object's `iceConnectionState` property.

One common task performed by the `iceconnectionstatechange` event listener is to trigger ICE restart when the state changes to `failed`.

This event is not cancelable and does not bubble.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("iceconnectionstatechange", (event) => {});

oniceconnectionstatechange = (event) => {};
```

Event type
----------

A generic `Event`.

Usage notes
-----------

A successful connection attempt will typically involve the state starting at `new`, then transitioning through `checking`, then `connected`, and finally `completed`. However, under certain circumstances, the `connected` state can be skipped, causing a connection to transition directly from the `checking` state to `completed`. This can happen when only the last checked candidate is successful, and the gathering and end-of-candidates signals both occur before the successful negotiation is completed.

### ICE connection state during ICE restarts

When an ICE restart is processed, the gathering and connectivity checking process is started over from the beginning, which will cause the `iceConnectionState` to transition to `connected` if the ICE restart was triggered while in the `completed` state. If ICE restart is initiated while in the transient `disconnected` state, the state transitions instead to `checking`, essentially indicating that the negotiation is ignoring the fact that the connection had been temporarily lost.

### State transitions as negotiation ends

When the negotiation process runs out of candidates to check, the ICE connection transitions to one of two states. If no suitable candidates were found, the state transitions to `failed`. If at least one suitable candidate was successfully identified, the state transitions to `completed`. The ICE layer makes this determination upon receiving the end-of-candidates signal, which is provided by calling `addIceCandidate()` with a candidate whose `candidate` property is an empty string (""), or by setting the `RTCPeerConnection` property `canTrickleIceCandidates` to `false`.

Examples
--------

An event handler for this event can be added using the `oniceconnectionstatechange` property or by using `addEventListener()` on the `RTCPeerConnection`.

In this example, a handler for `iceconnectionstatechange` is set up to update a call state indicator by using the value of `iceConnectionState` to create a string which corresponds to the name of a CSS class that we can assign to the status indicator to cause it to reflect the current state of the connection.

```js
pc.addEventListener(
  "iceconnectionstatechange",
  (ev) => {
    let stateElem = document.querySelector("#call-state");
    stateElem.className = `${pc.iceConnectionState}-state`;
  },
  false,
);
```

This can also be written as:

```js
pc.oniceconnectionstatechange = (ev) => {
  let stateElem = document.querySelector("#call-state");
  stateElem.className = `${pc.iceConnectionState}-state`;
};
```

Specifications
--------------

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-rtcpeerconnection-oniceconnectionstatechange |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebRTC API
* `RTCPeerConnection`
* `RTCPeerConnection.iceConnectionState`


RTCPeerConnection: addTransceiver() method - Web APIs

RTCPeerConnection: addTransceiver() method
==========================================

 The `RTCPeerConnection` method **`addTransceiver()`** creates a new `RTCRtpTransceiver` and adds it to the set of transceivers associated with the `RTCPeerConnection`.
 Each transceiver represents a bidirectional stream, with both an `RTCRtpSender` and an `RTCRtpReceiver` associated with it.

Syntax
------

```js
addTransceiver(trackOrKind)
addTransceiver(trackOrKind, init)
```

### Parameters

`trackOrKind`

 A `MediaStreamTrack` to associate with the transceiver, or a
 string which is used as the `kind` of the receiver's `track`, and by
 extension of the `RTCRtpReceiver` itself.

`init` Optional

 An object for specifying any options when creating the new transceiver.
 Possible values are:

`direction` Optional

The new transceiver's preferred directionality. This value is used to initialize the new `RTCRtpTransceiver` object's `RTCRtpTransceiver.direction` property.

`sendEncodings` Optional

 An array of encodings to allow when sending RTP media from the `RTCRtpSender`.
 This is the same as the `parameter.encodings` array passed to `RTCRtpSender.setParameters()`.

`streams` Optional

A list of `MediaStream` objects to add to the transceiver's `RTCRtpReceiver`; when the remote peer's `RTCPeerConnection`'s `track` event occurs, these are the streams that will be specified by that event.

### Return value

The `RTCRtpTransceiver` object which will be used to exchange the media data.

### Exceptions

`TypeError`

Thrown if `trackOrKind` was not either `"audio"` or `"video"`.

If the `sendEncodings` argument is used, this error may also be thrown if there is a badly formatted `rid` member, some but not all encodings contain a `rid` member, or different encodings have the same `rid` value.

`RangeError`

Thrown if any of the `sendEncodings` encodings have a `maxFramerate` value less than 0.0, or a `scaleResolutionDownBy` value of less than 1.0.

`InvalidStateError` `DOMException`

Thrown if the method is called when the associated connection is closed.

`InvalidAccessError` `DOMException`

Thrown if the `sendEncodings` argument is used, and contains a read-only parameter other than `rid`.

Specifications
--------------

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-rtcpeerconnection-addtransceiver |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebRTC API
* Introduction to the Real-time Transport Protocol (RTP)
* `RTCPeerConnection.addTrack()` also creates transceivers
* `RTCRtpReceiver` and `RTCRtpSender`


RTCPeerConnection: getTransceivers() method - Web APIs

RTCPeerConnection: getTransceivers() method
===========================================

The `RTCPeerConnection` interface's **`getTransceivers()`** method returns a list of the `RTCRtpTransceiver` objects being used to send and receive data on the connection.

Syntax
------

```js
getTransceivers()
```

### Parameters

None.

### Return value

 An array of the `RTCRtpTransceiver` objects representing the transceivers handling sending and receiving all media on the `RTCPeerConnection`.
 The array is in the order in which the transceivers were added to the connection.
 The array does not include transceivers that have already been stopped (following offer/answer).

Examples
--------

The following snippet of code stops all transceivers associated with an `RTCPeerConnection`.

```js
pc.getTransceivers().forEach((transceiver) => {
  transceiver.stop();
});
```

Specifications
--------------

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-peerconnection-gettranseceivers |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebRTC API
* Signaling and video calling
* `RTCPeerConnection.addTransceiver()`
* `Array.forEach()`


RTCPeerConnection: addTrack() method - Web APIs

RTCPeerConnection: addTrack() method
====================================

The `RTCPeerConnection` method **`addTrack()`** adds a new media track to the set of tracks which will be transmitted to the other peer.

**Note:** Adding a track to a connection triggers renegotiation by firing a `negotiationneeded` event.
 See Starting negotiation for details.

Syntax
------

```js
addTrack(track)
addTrack(track, stream1)
addTrack(track, stream1, stream2)
addTrack(track, stream1, stream2, /\* …, \*/ streamN)
```

### Parameters

`track`

A `MediaStreamTrack` object representing the media track to add to the peer connection.

`stream1`, …, `streamN` Optional

One or more local `MediaStream` objects to which the track should be added.

 The specified `track` doesn't necessarily have to already be part of any of the specified `stream`s.
 Instead, the `stream`s are a way to group tracks together on the receiving end of the connection, making sure they are synchronized.
 Any tracks that are added to the same stream on the local end of the connection will be on the same stream on the remote end.

### Return value

The `RTCRtpSender` object which will be used to transmit the media data.

**Note:** Every `RTCRtpSender` is paired with an `RTCRtpReceiver` to make up an `RTCRtpTransceiver`.
 The associated receiver is muted (indicating that it is not able to deliver packets) until and unless one or more streams are added to the receiver by the remote peer.

### Exceptions

`InvalidAccessError` `DOMException`

Thrown if the specified track (or all of its underlying streams) is already part of the `RTCPeerConnection`.

`InvalidStateError` `DOMException`

Thrown if the `RTCPeerConnection` is closed.

Usage notes
-----------

### Adding tracks to multiple streams

 After the `track` parameter, you can optionally specify one or more `MediaStream` objects to add the track to.
 Only tracks are sent from one peer to another, not streams.
 Since streams are specific to each peer, specifying one or more streams means the other peer will create a corresponding stream (or streams) automatically on the other end of the connection, and will then automatically add the received track to those streams.

#### Streamless tracks

 If no streams are specified, then the track is **streamless**.
 This is perfectly acceptable, although it will be up to the remote peer to decide what stream to insert the track into, if any.
 This is a very common way to use `addTrack()` when building many types of simple applications, where only one stream is needed.
 For example, if all you're sharing with the remote peer is a single stream with an audio track and a video track, you don't need to deal with managing what track is in what stream, so you might as well just let the transceiver handle it for you.

Here's an example showing a function that uses `getUserMedia()` to obtain a stream from a user's camera and microphone, then adds each track from the stream to the peer connection, without specifying a stream for each track:

```js
async function openCall(pc) {
  const gumStream = await navigator.mediaDevices.getUserMedia({
    video: true,
    audio: true,
  });
  for (const track of gumStream.getTracks()) {
    pc.addTrack(track);
  }
}
```

 The result is a set of tracks being sent to the remote peer, with no stream associations.
 The handler for the `track` event on the remote peer will be responsible for determining what stream to add each track to, even if that means adding them all to the same stream.
 The `ontrack` handler might look like this:

```js
let inboundStream = null;

pc.ontrack = (ev) => {
  if (ev.streams && ev.streams[0]) {
    videoElem.srcObject = ev.streams[0];
  } else {
    if (!inboundStream) {
      inboundStream = new MediaStream();
      videoElem.srcObject = inboundStream;
    }
    inboundStream.addTrack(ev.track);
  }
};
```

 Here, the `track` event handler adds the track to the first stream specified by the event, if a stream is specified.
 Otherwise, the first time `ontrack` is called, a new stream is created and attached to the video element, and then the track is added to the new stream.
 From then on, new tracks are added to that stream.

You could also just create a new stream for each track received:

```js
pc.ontrack = (ev) => {
  if (ev.streams && ev.streams[0]) {
    videoElem.srcObject = ev.streams[0];
  } else {
    let inboundStream = new MediaStream(ev.track);
    videoElem.srcObject = inboundStream;
  }
};
```

#### Associating tracks with specific streams

 By specifying a stream and allowing `RTCPeerConnection` to create streams for you, the streams' track associations are automatically managed for you by the WebRTC infrastructure.
 This includes things like changes to the transceiver's `direction` and tracks being halted using `removeTrack()`.

For example, consider this function that an application might use to begin streaming a device's camera and microphone input over an `RTCPeerConnection` to a remote peer:

```js
async function openCall(pc) {
  const gumStream = await navigator.mediaDevices.getUserMedia({
    video: true,
    audio: true,
  });
  for (const track of gumStream.getTracks()) {
    pc.addTrack(track, gumStream);
  }
}
```

The remote peer might then use a `track` event handler that looks like this:

```js
pc.ontrack = ({ streams: [stream] }) => (videoElem.srcObject = stream);
```

This sets the video element's current stream to the one that contains the track that's been added to the connection.

### Reused senders

 This method returns a new `RTCRtpSender` or an existing instance for reuse.
 An `RTCRtpSender` instance is only compatible for reuse if it meets the following criteria:

* There is no track already associated with the sender.
* The `RTCRtpTransceiver` associated with the sender has a `RTCRtpReceiver` whose `track` property specifies a `MediaStreamTrack` whose `kind` is the same as the `kind` of the `track` parameter specified when calling
 `RTCPeerConnection.addTrack()`. This ensures that a transceiver only handles audio or video and never both.
* The `RTCRtpTransceiver.currentDirection` property is not `"stopped"`.
* The `RTCRtpSender` being considered has never been used to send data.
 If the transceiver's `currentDirection` has ever been `"sendrecv"` or `"sendonly"`, the sender can't be reused.

If all of those criteria are met, the sender gets reused, which results in these changes occurring to the existing `RTCRtpSender` and its `RTCRtpTransceiver`:

* The `RTCRtpSender`'s `track` is set to the specified track.
* The sender's set of associated streams is set to the list of streams passed into this method, `stream...`.
* The associated `RTCRtpTransceiver` has its `currentDirection` updated to indicate that it is sending;
 if its current value is `"recvonly"`, it becomes `"sendrecv"`, and if its current value is `"inactive"`, it becomes `"sendonly"`.
### New senders

 If no existing sender exists that can be reused, a new one is created. This also
 results in the creation of the associated objects that must exist. The process of
 creating a new sender results in these changes:

* The new `RTCRtpSender` is created with the specified `track` and set of `stream`(s).
* A new `RTCRtpReceiver` is created with a *new* `MediaStreamTrack` as its `track` property (not the track specified as a parameter when calling `addTrack()`).
 This track's `kind` is set to match the `kind` of the track provided as an input parameter.
* A new `RTCRtpTransceiver` is created and associated with the new sender and receiver.
* The new transceiver's `direction` is set to `"sendrecv"`.
* The new transceiver is added to the `RTCPeerConnection`'s set of transceivers.
Examples
--------

 This example is drawn from the code presented in the article Signaling and video calling and its corresponding sample code.
 It comes from the `handleVideoOfferMsg()` method there, which is called when an offer message is received from the remote peer.

```js
const mediaConstraints = {
  audio: true, // We want an audio track
  video: true, // And we want a video track
};

const desc = new RTCSessionDescription(sdp);

pc.setRemoteDescription(desc)
  .then(() => navigator.mediaDevices.getUserMedia(mediaConstraints))
  .then((stream) => {
    previewElement.srcObject = stream;

    stream.getTracks().forEach((track) => pc.addTrack(track, stream));
  });
```

 This code takes SDP which has been received from the remote peer and constructs a new `RTCSessionDescription` to pass into `setRemoteDescription()`.
 Once that succeeds, it uses `MediaDevices.getUserMedia()` to obtain access to the local webcam and microphone.

If that succeeds, the resulting stream is assigned as the source for a `<video>` element which is referenced by the variable `previewElement`.

 The final step is to begin sending the local video across the peer connection to the caller.
 This is done by adding each track in the stream by iterating over the list returned by `MediaStream.getTracks()` and passing them to `addTrack()` along with the `stream` which they're a component of.

Specifications
--------------

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-rtcpeerconnection-addtrack |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebRTC
* Introduction to the Real-time Transport Protocol (RTP)
* `track`


RTCPeerConnection: peerIdentity property - Web APIs

RTCPeerConnection: peerIdentity property
========================================

 The read-only `RTCPeerConnection` property
 **`peerIdentity`** returns a JavaScript `Promise`
 that resolves to an `RTCIdentityAssertion` which contains a
 string identifying the remote peer. Once this promise
 resolves successfully, the resulting identity is the **target peer
identity** and cannot change for the duration of the connection.

Value
-----

 A JavaScript `Promise` which resolves to an
 `RTCIdentityAssertion` that describes the remote peer's identity.

 If an error occurs while attempting to validate an incoming identity assertion (that
 is, the information describing a peer's identity), the promise is rejected. If there
 isn't already a target peer identity, `peerIdentity` is set to a newly
 created promise and the process begins again, until the process succeeds or no further
 attempts to authenticate occur.

**Note:** The promise returned by
 `setRemoteDescription()` cannot
 resolve until any target peer identity that's been set is validated. If the identity
 hasn't been validated yet, the promise returned by `setRemoteDescription()`
 will be rejected. If there's no target peer identity,
 `setRemoteDescription()` doesn't need to wait for validation to occur
 before it resolves.

Examples
--------

 In this example, a function, `getIdentityAssertion()`, is created which
 asynchronously waits for the peer's identity to be verified, then returns the identity
 to the caller. If an error occurs and the promise is rejected, this logs the error to
 the console and returns `null` to the caller.

```js
let pc = new RTCPeerConnection();

// …

async function getIdentityAssertion(pc) {
  try {
    const identity = await pc.peerIdentity;
    return identity;
  } catch (err) {
    console.log("Error identifying remote peer: ", err);
    return null;
  }
}
```

Specifications
--------------

| Specification |
| --- |
| Identity for WebRTC 1.0 # dom-rtcpeerconnection-peeridentity |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebRTC API


RTCPeerConnection: getConfiguration() method - Web APIs

RTCPeerConnection: getConfiguration() method
============================================

 The **`RTCPeerConnection.getConfiguration()`** method returns
 an object which indicates the current configuration of
 the `RTCPeerConnection` on which the method is called.

 The returned configuration is the last configuration applied via
 `setConfiguration()`, or if
 `setConfiguration()` hasn't been called, the configuration the
 `RTCPeerConnection` was constructed with. The configuration includes a list
 of the ICE servers used by the connection, information about transport policies, and
 identity information.

Syntax
------

```js
getConfiguration()
```

### Parameters

This method takes no input parameters.

### Return value

An object describing the `RTCPeerConnection`'s current configuration. See `RTCPeerConnection()` for more information on what options are allowed.

Examples
--------

 This example adds a new certificate to an active connection if it doesn't already have
 one in use.

```js
let configuration = myPeerConnection.getConfiguration();

if (configuration.certificates?.length === 0) {
  RTCPeerConnection.generateCertificate({
    name: "RSASSA-PKCS1-v1\_5",
    hash: "SHA-256",
    modulusLength: 2048,
    publicExponent: new Uint8Array([1, 0, 1]),
  }).then((cert) => {
    configuration.certificates = [cert];
    myPeerConnection.setConfiguration(configuration);
  });
}
```

 This example fetches the current configuration of the `RTCPeerConnection`,
 then looks to see if it has any certificates set by examining whether or not (a) the
 configuration has a value for `certificates`, and (b) whether its length is
 zero.

 If it's determined that there are no certificates in place,
 `RTCPeerConnection.generateCertificate()` is called to create a new
 certificate; we provide a fulfillment handler which adds a new array containing the one
 newly-created certificate to the current configuration and passes it to
 `setConfiguration()` to add the
 certificate to the connection.

Specifications
--------------

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-rtcpeerconnection-getconfiguration |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `RTCPeerConnection.setConfiguration()`
* `RTCPeerConnection()`
* `RTCPeerConnection`