Skip to contentSkip to navigationSkip to topbar
On this page

Voice JS SDK v1: Twilio.Connection


(warning)

Warning

You're viewing the 1.X version of the Voice JavaScript SDK (formerly called Twilio Client). Click here for information on how to migrate to the 2.X version.

A Twilio.Connection object represents a call to or from Twilio. You never instantiate it directly, but it's passed to event handlers and returned when you call Twilio.Device.connect().

1
// Explicitly create a new outgoing connection
2
var connection = Twilio.Device.connect();
3
4
// or handle an incoming connection event
5
Twilio.Device.on('incoming', function(conn) {
6
// conn is a Twilio.Connection object
7
});

Method Reference

method-reference page anchor

.accept( [audioConstraints] )

accept page anchor

Accepts an incoming connection.

This will begin establishing the media session to this device. The connection status will be set to connecting while the media session for the call is setup. The connection status will change to open once the media session is established.

1
Twilio.Device.on('incoming', function(conn) {
2
conn.accept();
3
});

You can optionally specify an audioConstraints object to change the behavior of the local media stream during this call. You can use this to select a specific microphone, or turn off features like auto-gain control. Each web browser implements a different set of MediaTrackConstraints which may be used as audioConstraints, so consult your browser's implementation of getUserMedia for further details.

1
var audioConstraints = {
2
optional: [{ sourceId: 'XXX' }]
3
};
4
5
Twilio.Device.on('incoming', function(conn) {
6
conn.accept(audioConstraints);
7
});

Best Practice Note

best-practice-note page anchor

.accept( [audioConstraints] ) method calls getUserMedia to get an audio stream. The call will automatically disconnect if getUserMedia is not successful. For example, due to hardware or permission issues. It is recommended to handle getUserMedia errors before accepting a call. See best practice note here.

Reject a pending connection. This will cause a hangup to be issued from the client session to the dialing party. If multiple client sessions are active the pending connection will be rejected for all of them.

Ignore a pending connection. This will stop the Client device from playing the incoming sound and set the connection state to closed, but will not send a hangup message to the dialing party. The incoming call will keep ringing until another Client with the same name answers the call, or the call times out.

Close this connection.

.mute(bool)

mute page anchor

Mutes or unmutes the current connection based on the Boolean parameter you provide. true mutes the connection by ending audio gathered from the user's microphone, false unmutes the connection.

Returns a Boolean indicating whether the connection is muted.

Get the local MediaStream being used by the Connection. This contains the local Client's audio input.

.getRemoteStream()

getremotestream page anchor

Get the remote MediaStream. This contains the remote Client's audio, which is being received locally and output through the local Client's speakers.

.sendDigits( digits )

senddigits page anchor

Play DTMF tones. The digits parameter is a string and can contain the characters 0-9, *, #, and w. Each w will cause a 500 ms pause between digits sent. If you're familiar with TwiML, you can think of the sendDigits method as the sendDigits attribute in the <Number> noun. The SDK only supports sending DTMF digits. It does not raise events if DTMF digits are present in the incoming audio stream.

Return the status of this connection. The status will be one of the following strings:

Status valueDescription
"pending"The connection is incoming and hasn't yet been established.
"connecting"The connection has been accepted by or initiated by the local client.
"ringing"The callee has been notified of the call but has not yet responded. Note: Until 2.0, this state is only surfaced when the enableRingingState flag is set to true in Device.setup options and the TwiML app is dialing out with the answerOnBridge property, eg: <Dial answerOnBridge=true></Dial>.
"open"The connection has been established.
"closed"The connection has been disconnected.

.postFeedback(score, issue)

post-feedback page anchor

Posts the feedback collected for this call to Twilio. If no parameters are passed, Twilio will report feedback was not available for this call. Posting the feedback using this API will enable you to understand exactly which factors contribute to audio quality problems. Twilio will be able to correlate the metrics with perceived call quality and provide an accurate picture of the factors affecting your users' call experience.

ScoreSuggested Interpretation
1Terrible call quality, call dropped, or caused great difficulty in communicating.
2Bad call quality, like choppy audio, periodic one-way-audio.
3Average call quality, manageable with some noise/minor packet loss.
4Good call quality, minor issues.
5Great call quality. No issues.
Issue NameDescription
dropped-callCall initially connected but was dropped
audio-latencyParticipants can hear each other but with significant delay
one-way-audioOne participant couldn't hear the other
choppy-audioPeriodically, participants couldn't hear each other. Some words were lost.
noisy-callThere was disturbance, background noise, low clarity.
echoThere was echo during call.
1
.postFeedback(5); // Perfect call!
2
.postFeedback(2, 'dropped-call'); // Not so perfect... We'll do better next time!
3
.postFeedback(); // We asked the customer for feedback but they declined to provide feedback.

.on('accept', handler(connection))

accept-handler page anchor

Register a handler function to be called when this connection object has finished connecting and changes its state to open.

The handler function receives the Twilio.Connection object as its sole argument.

.on('audio', handler(remoteAudio))

audio-handler page anchor

Register a handler function to be called when the HTMLAudioElement for the remote audio is created. The handler function receives the HTMLAudioElement for the remote audio as its sole argument. This event can be used to redirect media if your environment supports it. See WebRTC redirection for more details.

.on('cancel', handler())

cancel-handler page anchor

Register a handler function to be called when the connection is cancelled and Connection.status() has transitioned to closed. This is raised when Connection.ignore() is called or when a pending invite while trying to connect to Twilio has been cancelled.

.on('disconnect', handler(connection))

disconnect-1 page anchor

Register a handler function to be called when this connection is closed.

The handler function receives the Twilio.Connection object as its sole argument.

1
var connection = Twilio.Device.connect();
2
3
connection.on('disconnect', function(conn) {
4
console.log("the call has ended");
5
});
6

.on('error', handler(error))

error page anchor

Register a handler function to be called when any device error occurs during the lifetime of this connection. These may be errors in your request, your capability token, connection errors, or other application errors. See the Twilio Client error code reference for more information. Using the error handler is a great way to debug your application and help catch mistakes in your code!

The handler function receives an error object as an argument. The error object may include the following properties:

PropertyDescription
messageA string describing the error.
codeA numeric error code described in the Twilio Client error code reference.
connectionA reference to the Twilio.Connection object that was active when the error occurred.
twilioErrorWhen applicable, errors emitted now contain this twilioError field, providing more information about the error. This twilioError represents the new TwilioError format that will become the default Error format in the next major release. To get a list of possible twilioErrors, please visit this page(link takes you to an external page).

.on('mute', handler(boolean, connection))

mute-handler page anchor

Register a handler function to be called when a connection is muted or unmuted.

The handler function receives a Boolean indicating whether the connection is now muted (true) or not (false), and the Twilio.Connection object that was muted or unmuted.

.on('reconnecting', handler(error))

onreconnecting-handlererror page anchor

Note: This feature is behind a flag on Device.setup: enableIceRestart. By default, this event will not fire.

Raised when media connection fails and automatic reconnection has been started by issuing ICE Restarts. During this period, Connection.status() will be set to reconnecting.

.on('reconnected', handler())

onreconnected-handler page anchor

Note: This feature is behind a flag on Device.setup: enableIceRestart. By default, this event will not fire.

Raised when media connection has been restored which is detected when media starts flowing. Once reconnected, Connection.status() will be set to open.

.on('reject', handler())

reject-handler page anchor

Register a handler function to be called when the connection is rejected and Connection.status() has transitioned to closed. This is raised when Connection.reject() is called.

.on('ringing', handler(hasEarlyMedia))

onringing-handlerhasearlymedia page anchor

Note: This feature is behind a flag on Device.setup: enableRingingState. By default, this event will not fire.

Raised when the Connection has entered the ringing state. By default, TwiML's Dial verb will connect immediately and this state will be brief or skipped entirely. When using the Dial verb with answerOnBridge=true, the ringing state will begin when the callee has been notified of the call and will transition into open after the callee accepts the call, or closed if the call is rejected or cancelled.

The hasEarlyMedia argument is a Boolean denoting whether there is early media available from the callee. If true, the Client SDK will automatically play the early media — Sometimes this is ringing, other times it may be an important message about the call. If false, there is no remote media to play, so the application may want to play its own outgoing ringtone sound.

1
connection.on('ringing', function(hasEarlyMedia) {
2
showRingingIndicator();
3
if (!hasEarlyMedia) { playOutgoingRinging(); }
4
});

.on('sample', handler(rtcSample)

sample page anchor

Register a handler function to be called when the Connection gets a WebRTC sample object. This event is published every second.

1
{
2
"audioInputLevel": 11122,
3
"audioOutputLevel": 2138,
4
"bytesReceived": 8600,
5
"bytesSent": 8600,
6
"codecName": "opus",
7
"jitter": 0,
8
"mos": 4.397229249317001,
9
"packetsLost": 0,
10
"packetsLostFraction": 0,
11
"packetsReceived": 50,
12
"packetsSent": 50,
13
"rtt": 77,
14
"timestamp": 1572301567032.327,
15
"totals": {
16
"bytesReceived": 63640,
17
"bytesSent": 83936,
18
"packetsLost": 0,
19
"packetsLostFraction": 0,
20
"packetsReceived": 370,
21
"packetsSent": 488
22
}
23
}

.on('volume', handler(inputVolume, outputVolume))

volume page anchor

Register a handler function to be called with the Connection's current input volume and output volume on every animation frame(link takes you to an external page). The handler will be invoked up to 60 times per second, and will scale down dynamically on slower devices to preserve performance. The handler receives inputVolume and outputVolume as percentages of maximum volume represented by a floating point number between 0.0 and 1.0, inclusive. This value represents a range of relative decibel values between -100dB and -30dB.

.on('warning', handler(warningName, warningData))

onwarning-handlerwarningname-warningdata page anchor

Raised when a call-quality-metric has crossed a threshold.

Twilio.js raises warning events when it detects a drop in call quality or other conditions that may indicate the user is having trouble with the call. You can implement callbacks on these events to alert the user of an issue.

For a full list of warning events, check the Voice Insights events reference. Check the examples below to see how to listen to warning and warning-cleared events.

1
connection.on('warning', function(warningName, warningData) {
2
if (warningName === 'low-mos') {
3
showQualityWarningModal('We have detected poor call quality conditions. You may experience degraded call quality.');
4
console.log(warningData);
5
/* Prints the following
6
{
7
// Stat name
8
"name": "mos",
9
10
// Array of mos values in the past 5 samples that triggered the warning
11
"values": [2, 2, 2, 2, 2],
12
13
// Array of samples collected that triggered the warning.
14
// See sample object format here https://www.twilio.com/docs/voice/sdks/javascript/v1/connection#sample
15
"samples": [...],
16
17
// The threshold configuration.
18
// In this example, low-mos warning will be raised if the value is below 3
19
"threshold": {
20
"name": "min",
21
"value": 3
22
}
23
}
24
*/
25
}
26
});

.on('warning-cleared', handler(warningName))

onwarning-cleared-handlerwarningname page anchor

Raised when a call-quality-metric has returned to normal.

1
connection.on('warning-cleared', function(warningName) {
2
if (warningName === 'low-mos') {
3
hideQualityWarningModal();
4
}
5
});

.callerInfo returns caller verification information about the caller. If no caller verification information is available this will return null. The callerInfo object contains the following attributes:

  • isVerified - Indicates whether or not the caller's phone number has been verified by Twilio using SHAKEN/STIR. True if the caller has been verified at level 'A', false if the caller has been verified at any lower level or has failed verification.

Example

1
device.on('incoming', connection => {
2
if (connection.callerInfo && connection.callerInfo.isVerified) {
3
console.log('This caller is verified by a carrier under the SHAKEN and STIR call authentication framework');
4
}
5
});

Check out this page to learn more about making and receiving SHAKEN/STIR calls to/from the public telephone network.

.customParameters is a Map<string, string> that includes all TwiML parameters sent to or received from the TwiML app this Connection is connecting to. This feature is a great way to pass context data between your TwiML app and the JS Client SDK.

An incoming Connection's .customParameters contains all of the data sent using <Parameter> nouns in the TwiML app.

An outgoing Connection's .customParameters contains all of the TwiML parameters data passed in to Device.connect(twimlParams). It's important to note that a caller's .customParameters Map and a callee's .customParameters Map may not contain the same data, because it's up to your TwiML app to choose which, if any, of the data it receives from the caller to pass to the callee.

.parameters contains details about the call, such as who is calling and what was dialed. The meaning of these parameters matches those in the Twilio Voice request parameters.

On incoming connections, the following parameters are included:

ParameterDescription
CallSidA unique identifier for this call, generated by Twilio.
AccountSidYour Twilio account ID. It is 34 characters long, and always starts with the letters AC.
FromThe phone number or client identifier of the party that initiated the call. Phone numbers are formatted with a '+' and country code, e.g. +16175551212 ([E.164][e164] format). Client identifiers begin with the client: URI scheme; for example, for a call from a client named 'tommy', the From parameter will be client:tommy.
ToThe phone number or client identifier of the called party. Phone numbers are formatted with a '+' and country code, e.g. +16175551212 ( [E.164][e164] format). Client identifiers begin with the client: URI scheme; for example, for a call to a client named 'joey', the To parameter will be client:joey.
ApiVersionThe version of the Twilio API used to handle this call. For incoming calls, this is determined by the API version set on the called number. For outgoing calls, this is the API version used by the outgoing call's REST API request.

On outgoing connections, the following parameters are included:

ParameterDescription
CallSidA unique identifier for this call, generated by Twilio.


(error)

Danger

The following methods have been deprecated and will be removed in a future release of twilio.js. Calling these methods will generate a deprecation warning unless the warnings parameter is set to false when calling Twilio.Device.setup().


Stop capturing audio from the microphone for this connection. This method has been replaced by .mute(bool).


Resume capturing audio from the microphone for this connection. This method has been replaced by .mute(bool).


Additionally, Twilio Client is moving toward the standard EventEmitter(link takes you to an external page) interface, meaning events should be managed with .on(eventName, handler) and .removeListener(eventName, handler), replacing our legacy handlers (such as .accept(handler), .error(handler), etc...). The following methods are deprecated:

1
Connection.accept(handler)
2
Connection.cancel(handler)
3
Connection.disconnect(handler)
4
Connection.error(handler)
5
Connection.ignore(handler)
6
Connection.mute(handler)
7
Connection.reject(handler)
8
Connection.volume(handler)

These have been replaced with the following EventEmitter events:

1
Connection.on('accept', handler)
2
Connection.on('cancel', handler)
3
Connection.on('disconnect', handler)
4
Connection.on('error', handler)
5
Connection.on('mute', handler)
6
Connection.on('reject', handler)
7
Connection.on('volume', handler)

Note that there is no ignore event. The .ignore(handler) method is actually a backward-compatible listener for the .on('cancel', handler) event.

Need some help?

Terms of service

Copyright © 2024 Twilio Inc.