RTCPeerConnection: addIceCandidate() method
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2017.
TheaddIceCandidate() method of theRTCPeerConnection interface adds a new remote candidate to the connection's remote description, which describes the state of the remote end of the connection.
When a website or app usingRTCPeerConnection receives a new ICE candidate from the remote peer over its signaling channel, it delivers the newly-received candidate to the browser'sICE agent by callingRTCPeerConnection.addIceCandidate().This adds this new remote candidate to theRTCPeerConnection's remote description, which describes the state of the remote end of the connection.
If thecandidate parameter is missing or a value ofnull is given when callingaddIceCandidate(), the added ICE candidate is an "end-of-candidates" indicator.The same is the case if the value of the specified object'scandidate 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 ofend-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 articlesWebRTC connectivity andSignaling and video calling.
In this article
Syntax
addIceCandidate(candidate)addIceCandidate(candidate, successCallback) // deprecatedaddIceCandidate(candidate, successCallback, failureCallback) // deprecatedParameters
candidateOptionalAn
RTCIceCandidateobject, or an object that has the following properties:candidateOptionalA string describing the properties of the candidate, taken directly from theSDP attribute
"candidate".The candidate string specifies the network connectivity information for the candidate.If thecandidateis 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 inRFC 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
candidatestring's value will be:"candidate:4234997325 1 udp 2043278322 192.0.2.172 44323 typ host"`
Theuser agent always prefers candidates with the highest
priority, all else being equal.In the example above, the priority is2043278322. 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= 4234997325component="rtp"(the number 1 is encoded to this string; 2 becomes"rtcp")protocol="udp"priority= 2043278322ip="192.0.2.172"port= 44323type="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.
sdpMidOptionalA string containing the identification tag of the media stream with which the candidate is associated, or
nullif there is no associated media stream. The default isnull.Additional information can be found in
RTCIceCandidate.sdpMid.sdpMLineIndexOptionalA number property containing the zero-based index of the m-line with which the candidate is associated, within theSDP of the media description, or
nullif no such associated exists. The default isnull.Additional information can be found in
RTCIceCandidate.sdpMLineIndex.usernameFragmentOptionalA 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 theSTUN 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
TypeErrorexception if bothsdpMidandsdpMLineIndexarenull.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
candidateobject is specified, or its value isnull, an end-of-candidates signal is sent to the remote peer using theend-of-candidatesa-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 isstrongly discouraged.You should update any existing code to use thePromise-based version ofaddIceCandidate() instead.The parameters for the older form ofaddIceCandidate() are described below, to aid in updating existing code.
successCallbackDeprecatedA function to be called when the ICE candidate has been successfully added.This function receives no input parameters and doesn't return a value.
failureCallbackDeprecatedA function to be called if attempting to add the ICE candidate fails.Receives as input a
DOMExceptionobject describing why failure occurred.
Return value
APromise 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, thePromise returned by this method is rejected, returning one of the errors below as thename attribute in the specifiedDOMException object passed to the rejection handler.
TypeErrorReturned if the specified candidate's
sdpMidandsdpMLineIndexare bothnull.InvalidStateErrorDOMExceptionReturned if the
RTCPeerConnectioncurrently has no remote peer established (remoteDescriptionisnull).OperationErrorDOMExceptionReturned in one of the following situations:
- The value specified for
sdpMidis non-nulland doesn't match the media description ID of any media description included within theremoteDescription. - The specified value of
sdpMLineIndexis greater than or equal to the number of media descriptions included in the remote description. - The specified
ufragdoesn't match theufragfield in any of the remote descriptions being considered. - One or more of the values in the
candidatestring are invalid or could not be parsed. - Attempting to add the candidate fails for any reason.
- The value specified for
Examples
This code snippet shows how to signal ICE candidates across an arbitrary signaling channel.
// 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:
pc.addIceCandidate({ candidate: "" });However, in most cases you won't need to look for this explicitly, since the events driving theRTCPeerConnection will deal with it for you, sending the appropriate events.
Specifications
| Specification |
|---|
| WebRTC: Real-Time Communication in Browsers> # dom-peerconnection-addicecandidate> |