recursal/MDN huggingface dataset:
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
=============================================

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
=====================================

**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
==============================================

 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
====================================

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
=============================================

 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
===========================================

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: 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
===========================================

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: 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
============================================

 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`