Skip to contentSkip to navigationSkip to topbar
Rate this page:
On this page

Voice JavaScript SDK: Twilio.Device


(information)

Info

You're viewing the documentation for the 2.X version of the Voice JavaScript SDK. View the Migration Guide to learn how to migrate from 1.X to 2.X or view the 1.x-specific documentation.

(information)

Info

The Twilio Client JavaScript SDK has been renamed to Twilio Voice JavaScript SDK.

The Device object is available when the JavaScript SDK is included in your application. It represents a softphone that communicates with Twilio to facilitate inbound and outbound audio connections.

For the full API reference, view the autogenerated documentation on GitHub(link takes you to an external page).

(warning)

Warning

Throughout this page, you will see device with a lowercase "d" and Device with an uppercase "D".

Device refers to the Device object provided by the SDK.

device represents an instance of a Device, created with the new keyword:


_10
const device = new Device(token);


Table of Contents

table-of-contents page anchor

A new instance of a Device should be constructed by using the new keyword and passing an Access Token as the first argument. The constructor also takes an optional second argument, DeviceOptions.

No signaling channel will be opened when instantiating a new Device. The signaling WebSocket will be opened when either device.register() or device.connect() are called.

(warning)

Warning

The maximum number of characters for the identity provided in the Access Token is 121. The identity may only contain alpha-numeric and underscore characters. Other characters, including spaces, or exceeding the maximum number of characters, will result in not being able to place or receive calls.

Instantiate a Device without DeviceOptions

instantiate-a-device-without-deviceoptions page anchor

_10
const device = new Device(token);

The DeviceOptions parameter is optional. The Device instance's options can be updated after instantiation using the device.updateOptions() method.

Instantiate a Device with DeviceOptions

instantiate-a-device-with-deviceoptions page anchor

Examples of using DeviceOptions to specify an Edge location:


_10
// Instantiate the device with a specified edge location
_10
const device = new Device(token, { edge: 'ashburn'};
_10
_10
// Instantiate the device with a specified edge and auto-fallback functionality
_10
const device = new Device(token, { edge: ['ashburn', 'sydney'] };

To see all of the possible properties, see the DeviceOptions section below.


The Device instance can be configured using the DeviceOptions parameter in two ways: during instantiation with the new keyword or by calling device.updateOptions().


_12
const deviceOptions = {
_12
edge: 'ashburn',
_12
}
_12
_12
// pass the options object as the second argument in Device constructor
_12
const device = new Device(token, deviceOptions);
_12
_12
// or
_12
_12
// use the updateOptions method after instantiating the device
_12
const device = new Device(token);
_12
device.updateOptions(deviceOptions);

DeviceOptions is a JavaScript object with the properties listed in the table below. All properties are optional.

Options PropertyDescription
allowIncomingWhileBusy Boolean

default: false
Whether the Device instance should raise the 'incoming' event when a new call invite is received while already on an active call.
appName stringA name for the application that is instantiating the Device instance. This is used to improve logging in Insights.
appVersion stringA version for the application that is instantiating the Device instance. This is used to improve logging in Insights.
closeProtection Boolean or string

default: false
Setting this property to true will enable a dialog prompt with the text "A call is currently in progress. Leaving or reloading the page will end the call." when closing a page which has an active connection. Setting the property to a string will create a custom message prompt with that string. If custom text is not supported by the browser, Twilio will display the browser's default dialog.
codecPreferences string[]

default:["pcmu", "opus"]
An array of codec names ordered from most-preferred to least-preferred. Opus and PCMU are the two codecs currently supported by Twilio Voice JS SDK. Opus can provide better quality for lower bandwidth, particularly noticeable in poor network conditions. Examples: ["opus", "pcmu"], ["pcmu"]
disableAudioContextSounds BooleanWhether AudioContext(link takes you to an external page) sounds should be disabled. Useful for troubleshooting sound issues that may be caused by AudioContext-specific sounds. If set to true, the Device instance will fall back to HTMLAudioElement(link takes you to an external page) sounds.
dscp BooleanWhether to use googDscp in RTC constraints
edge string[] or string

default: "roaming"
The Edge location to connect to. If using an array of edges, sort by highest priority to lowest priority. The array will be used to provide auto fallback functionality. Check the Device instance's current edge using the device.edge read-only property. If the Device instance is offline, the edge will be null. See the Edges documentation for more details.
enableImprovedSignalingErrorPrecision Boolean

default: false
When set to true, some errors that would have been described with a generic error code are now described with a more precise error code. Please see this section for more details.
enumerateDevices functionPass a custom enumerateDevices function to override what Twilio uses when requesting a list of available media input and output devices.
forceAggressiveIceNomination Boolean

default: false
Experimental feature. Sets whether the Device instance should use ICE Aggressive nomination(link takes you to an external page). If your deployment is on devices with one network interface and your Round Trip Time (RTT) to Twilio's Servers is typically greater than 96 milliseconds, this feature may help reduce call connect time. As this is an experimental feature, we don't recommend enabling this until after testing it thoroughly in your deployment.
getUserMedia functionPass a custom getUserMedia function to override what Twilio uses to create an input MediaStream.
logLevel number or stringThe Voice JavaScript SDK exposes a loglevel(link takes you to an external page)-based logger to allow for runtime logging configuration. Possible values include any of the following numbers: 0 = trace, 1 = debug, 2 = info, 3 = warn, 4 = error, 5 = silent Or any of the following strings: 'trace', 'debug', 'info', 'warn', 'error', 'silent' 'TRACE', 'DEBUG', 'INFO', 'WARN', 'ERROR', 'SILENT' See the loglevel docs(link takes you to an external page) for more information.
maxAverageBitrate numberMax average bitrate to better control how much bandwidth your VoIP application should use. See RFC-7587 section 7.1(link takes you to an external page). Only applicable when using Opus codec. By default, the Opus codec is set up with a transmission rate of around 32 kbps (40-50kbps on the wire). Max Average Bitrate can be set to as low as 6000 bps and as high as 510000 bps. Values outside this range are ignored and the default Opus operation mode is used. Lowering the max average bitrate impacts audio quality. The recommended bitrate for speech is between 8000 and 40000 bps. If you set maxAverageBitrate to 0, the setting is not used.
maxCallSignalingTimeoutMs number

default: 0
The maximum duration in milliseconds the Twilio.Device will attempt to reconnect to the most-recently-used edge in the event of a signaling connectivity loss. After the provided time has passed during reconnection attempts, the Twilio.Device will then use edge fallback. The default value of 0 means that signaling reconnection may not occur, since a change of edge during a reconnection attempt will cause a Call to fail. Since the Twilio.Device will only attempt to reestablish connectivity for up to 30 seconds, the maximum value you would want to use here is 30000 milliseconds. Note: This property is only related to users relying on edge fallback and some users using the 'roaming' edge. Read more about edge fallback and signaling reconnection on the Edge Locations page.
RTCPeerConnection functionOverrides the native RTCPeerConnection class. By default, the SDK will use the unified-plan SDP format if the browser supports it. Unexpected behavior may happen if the RTCPeerConnection parameter uses an SDP format that is different than what the SDK uses. For example, if the browser supports unified-plan and the RTCPeerConnection parameter uses plan-b by default, the SDK will use unified-plan which will cause conflicts with the usage of the RTCPeerConnection. In order to avoid this issue, you need to explicitly set the SDP format that you want the SDK to use with the RTCPeerConnection via Device.ConnectOptions.rtcConfiguration for outgoing calls. Or Call.AcceptOptions.rtcConfiguration for incoming calls. See the example below. Assuming the RTCPeerConnection you provided uses plan-b by default, the following code sets the SDP format to unified-plan instead.// Outgoing calls const call = await device.connect({ rtcConfiguration: { sdpSemantics: 'unified-plan' } // Other options }); // Incoming calls device.on('incoming', call => { call.accept({ rtcConfiguration: { sdpSemantics: 'unified-plan' } // Other options }); });
sounds objectA JavaScript object with key/value pairs of sound names (as the key) and URLs (as the value). See the deviceOptions.sounds properties section below for all available properties (keys for the deviceOptions.sounds object) and the default sounds provided by the SDK. Note: The incoming ringtone will loop for at least two seconds and as long as the incoming call is pending. All other sounds will play once; DTMF tones will be cut short if they exceed one second, while outgoing and disconnect sounds will be cut short if they exceed three seconds.
tokenRefreshMs number

default: 10000
The number of milliseconds before the AccessToken's expiry that the Twilio.Device will emit the 'tokenWillExpire' event. The default is 10 seconds (10000 milliseconds).

Example:

Specify an Edge location using DeviceOptions


_10
// pass options object during device instantiation
_10
const device = new Device(token, { edge: 'ashburn' });
_10
_10
// or
_10
_10
// pass options object using the updateOptions method
_10
const device = new Device(token);
_10
device.updateOptions({ edge: 'ashburn' });

Example:

Specify an Edge location and custom sounds


_18
const deviceOptions = {
_18
edge: 'ashburn',
_18
sounds: {
_18
incoming: 'http://mysite.com/incoming.mp3',
_18
outgoing: 'http://mysite.com/outgoing.mp3',
_18
dtmf8: 'http://mysite.com/8_button.mp3'
_18
}
_18
}
_18
_18
_18
// pass options object during device instantiation
_18
const device = new Device(token, deviceOptions);
_18
_18
// or
_18
_18
// pass options object using the updateOptions method
_18
const device = new Device(token);
_18
device.updateOptions(deviceOptions);

deviceOptions.sounds properties and default sounds

deviceoptionssounds-properties-and-default-sounds page anchor

The available properties on the deviceOptions.sounds object are listed in the left column of the table below. In the right column, there are audio players to hear the default sounds provided by the Voice JavaScript SDK.

deviceOptions.sounds propertyDefault sound
incoming

Listen to the default incoming sound

Your browser does not support the audio element.(link takes you to an external page)

outgoing

Listen to the default outgoing sound

Your browser does not support the audio element.(link takes you to an external page)

disconnect

Listen to the default disconnect sound

Your browser does not support the audio element.(link takes you to an external page)

dtmf1

Listen to the default dtmf1 sound

Your browser does not support the audio element.(link takes you to an external page)

dtmf2

Listen to the default dtmf2 sound

Your browser does not support the audio element.(link takes you to an external page)

dtmf3

Listen to the default dtmf3 sound

Your browser does not support the audio element.(link takes you to an external page)

dtmf4

Listen to the default dtmf4 sound

Your browser does not support the audio element.(link takes you to an external page)

dtmf5

Listen to the default dtmf5 sound

Your browser does not support the audio element.(link takes you to an external page)

dtmf6

Listen to the default dtmf6 sound

Your browser does not support the audio element.(link takes you to an external page)

dtmf7

Listen to the default dtmf7 sound

Your browser does not support the audio element.(link takes you to an external page)

dtmf8

Listen to the default dtmf8 sound

Your browser does not support the audio element.(link takes you to an external page)

dtmf9

Listen to the default dtmf9 sound

Your browser does not support the audio element.(link takes you to an external page)

dtmf0

Listen to the default dtmf0 sound

Your browser does not support the audio element.(link takes you to an external page)

dtmfs

Listen to the default dtmfs (star) sound

Your browser does not support the audio element.(link takes you to an external page)

dtmfh

Listen to the default dtmfh (hash) sound

Your browser does not support the audio element.(link takes you to an external page)

Improved Signaling Errors

improved-signaling-errors page anchor

When deviceOptions.enableImprovedSignalingErrorPrecision is set to true, the following errors that would have been described with a generic error code are now described with a more precise error code. With this feature, the following errors now have their own error codes. Please see this page for more details about each error.

Device Error Changes


_10
const device = new Device(token, {
_10
enableImprovedSignalingErrorPrecision: true,
_10
});
_10
device.on('error', (deviceError) => {
_10
// the following table describes how deviceError will change with this feature flag
_10
});

Device Error NameFlag EnabledFlag Disabled
GeneralErrors.ApplicationNotFoundError3100153000
GeneralErrors.ConnectionDeclinedError3100253000
GeneralErrors.ConnectionTimeoutError3100353000
MalformedRequestErrors.MissingParameterArrayError3110153000
MalformedRequestErrors.AuthorizationTokenMissingError3110253000
MalformedRequestErrors.MaxParameterLengthExceededError3110353000
MalformedRequestErrors.InvalidBridgeTokenError3110453000
MalformedRequestErrors.InvalidClientNameError3110553000
MalformedRequestErrors.ReconnectParameterInvalidError3110753000
SignatureValidationErrors.AccessTokenSignatureValidationFailed3120253000
AuthorizationErrors.NoValidAccountError3120353000
AuthorizationErrors.JWTTokenExpirationTooLongError3120753000
ClientErrors.NotFound3140453000
ClientErrors.TemporarilyUnavilable3148053000
ClientErrors.BusyHere3148653000
SIPServerErrors.Decline3160353000

Call Error Changes


_10
const device = new Device(token, {
_10
enableImprovedSignalingErrorPrecision: true,
_10
});
_10
const call = device.connect(...);
_10
call.on('error', (callError) => {
_10
// the following table describes how callError will change with this feature flag
_10
});

Call Error NameFlag EnabledFlag Disabled
GeneralErrors.ConnectionDeclinedError3100231005
AuthorizationErrors.InvalidJWTTokenError3120431005
AuthorizationErrors.JWTTokenExpiredError3120531005

This section contains descriptions of the methods available on a Device instance.

device.addListener(eventName, listener)

deviceaddlistenereventname-listener page anchor

Add an event listener to the Device instance. This is an alias for device.on().

See the Events section of this page to see the full list of events emitted by a Device instance.

ParameterData TypeDescription
eventNamestring or symbolThe event emitted by the Device instance that will call the listener function
listenerfunctionThe function that will be called when the specified event is emitted

Example:

If you want to know when your Device instance is ready to receive incoming calls, listen for the 'registered' event.


_10
const device = new Device(token);
_10
_10
device.addListener('registered', device => {
_10
console.log('The device is ready to receive incoming calls.')
_10
});

See the Node.js Events Docs(link takes you to an external page) for more information.

device.connect(ConnectOptions)

deviceconnectconnectoptions page anchor

Attempts a new connection to the Twilio application that you associated with the Access Token used when instantiating the Device instance.

This method will return a Promise with a Call object. You should keep track of this Call object to monitor/modify the active call.

To end the call, you can use the .disconnect() method on the Call object or use the device.disconnectAll() method.


_10
const device = new Device(token);
_10
_10
let call = await device.connect({
_10
params: {
_10
To: '+15551234567'
_10
}
_10
});

ConnectOptions

connectoptions page anchor

device.connect() takes an optional ConnectOptions argument. The ConnectOptions object is a JavaScript object with optional params, rtcConfiguration, and rtcConstraints properties.

Example:


_19
const device = new Device(token);
_19
_19
let call = await device.connect({
_19
params: {
_19
To: "+15551234567"
_19
agent: "Smith",
_19
location: "Matrix"
_19
},
_19
rtcConstraints: {
_19
audio: true
_19
},
_19
rtcConfiguration: {
_19
iceServers: [{
_19
urls: "stunserver.example.com",
_19
username: "username@twilio.com",
_19
credential: "webrtcCredential"
_19
}]
_19
}
_19
})

params property

A JavaScript object containing key/value pairs to be sent to the Twilio application. These params will be passed to your application as GET or POST parameters.

(warning)

Warning

The total length of all params passed to device.connect() must not exceed 800 bytes. See How to Share Information Between Your Applications for more information.

(warning)

Warning

Your application should not assume that these parameters are safe since any user can call this function with whatever parameters they want.

For example, the following code will pass the params key/value pairs agent=Smith and location=Matrix to the Twilio application associated with this Device instance's Access Token.


_10
const device = new Device(token);
_10
_10
let call = await device.connect({
_10
params: {
_10
agent: "Smith",
_10
location: "Matrix"
_10
}
_10
});

rtcConfiguration property

An RTCConfiguration(link takes you to an external page) dictionary to pass to the RTCPeerConnection(link takes you to an external page) constructor. This allows you to configure the WebRTC connection between your local machine and the remote peer.

rtcConstraints property

A MediaStreamConstraints(link takes you to an external page) dictonary to pass to getUserMedia(link takes you to an external page) when making or accepting a Call. This allows you to configure the behavior of tracks returned in the MediaStream(link takes you to an external page).

Each browser implements a different set of MediaTrackConstraints, so consult your browser's implementation of getUserMedia for more information.

Destroys the Device instance.

This method will disconnect all calls, unbind audio devices, destroy the stream (which causes the unregistered event to be emitted), and then the Device instance will emit the destroyed event. Then, all event listeners attached to the Device instance are cleaned up.


_10
const device = new Device(token);
_10
_10
device.destroy();

device.disconnectAll()

devicedisconnectall page anchor

Disconnect all Calls associated with the Device instance.

Example:

A user clicks on a Hang Up button in the browser, which calls device.disconnectAll() to end the current Call.


_10
const device = new Device(token);
_10
_10
// A click on a 'Hang Up' button calls this method
_10
const hangupCall = () => {
_10
device.disconnectAll();
_10
console.log('The call has ended.');
_10
}

device.emit(eventName, ...args)

deviceemiteventname-args page anchor

Calls each of the event listeners registered for the event named eventName. The listeners will be called in the order they were registered. Any arguments passed in after the eventName will be passed to the event listeners.

ParameterData TypeDescription
eventNamestring or symbolThe event emitted by the Device instance that will call the listener function
argsanyThe arguments that will be passed to the event listener(s) for the specified event

See the Node.js Events Docs(link takes you to an external page) for more information.

device.eventNames()

deviceeventnames page anchor

Returns an array of event names for which the Device instance has registered event listeners.

See the Node.js Events Docs(link takes you to an external page) for more information.

device.getMaxListeners()

devicegetmaxlisteners page anchor

Returns the current maximum number of event listeners for the Device instance.

By default, the maximum number of listeners is 10, and is set by the static Device.defaultMaxListeners property or the dynamic device.setMaxListeners(number) method.

See the Node.js Events Docs(link takes you to an external page) for more information.

device.listenerCount(eventName)

devicelistenercounteventname page anchor

Returns the number of listeners listening to the event named eventName on the Device instance.

ParameterData TypeDescription
eventNamestring or symbolThe name of the event for which you want to retrieve the listener count

See the Node.js Events Docs(link takes you to an external page) for more information.

device.listeners(eventName)

devicelistenerseventname page anchor

Returns an array of the listeners registered on the Device instance for the event named eventName.

ParameterData TypeDescription
eventNamestring or symbolThe name of the event for which you want to retrieve the listeners

See the Node.js Events Docs(link takes you to an external page) for more information.

device.off(eventName, listener)

deviceoffeventname-listener page anchor

Removes the listener for the event named eventName. This is an alias for device.removeListener().


_10
const device = new Device(token);
_10
_10
const handleSuccessfulRegistration = () => {
_10
console.log('The device is ready to receive incoming calls.')
_10
}
_10
_10
device.on('registered', handleSuccessfulRegistration);
_10
_10
device.off('registered', handleSuccessfulRegistration);

See the Node.js Event Docs(link takes you to an external page) for more information.

device.on(eventName, listener)

deviceoneventname-listener page anchor

Add an event listener to the Device instance. This is analogous to the Device.addListener() method.

See the Events section of this page to see the full list of events emitted by the Device instance.

ParameterData TypeDescription
eventNamestring or symbolThe event emitted by the Device instance that will call the listener function
listenerfunctionThe function that will be called when the specified event is emitted

Example:

If you want to know when your Device instance is ready to receive incoming calls, listen for the 'registered' event.


_10
const device = new Device(token);
_10
_10
device.on('registered', device => {
_10
console.log('The device is ready to receive incoming calls.')
_10
};

device.once(eventName, listener)

deviceonceeventname-listener page anchor

Adds a one-time listener to the Device instance for the event named eventName.

ParameterData TypeDescription
eventNamestring or symbolThe event emitted by the Device instance that will call the listener function
listenerfunctionThe function that will be called when the specified event is emitted. The listener function will be removed and then invoked one time.

See the Node.js Events Docs(link takes you to an external page) for more information.

device.prependListener(eventName, listener)

deviceprependlistenereventname-listener page anchor

Adds a listener function to the beginning of the listeners array for the event named eventName.

Calling this multiple times with the same eventName and listener arguments will add the listener again, meaning that the listener will be called multiple times when the specified event is emitted.

ParameterData TypeDescription
eventNamestring or symbolThe event emitted by the Device instance that will call the listener function
listenerfunctionThe function that will be called when the specified event is emitted. The listener will be added to the beginning of the listeners array for the specified event.

See the Node.js Events Docs(link takes you to an external page) for more information.

device.prependOnceListener(eventName, listener)

deviceprependoncelistenereventname-listener page anchor

Adds a one-time listener to the beginning of the listener array for the specified event.

ParameterData TypeDescription
eventNamestring or symbolThe event emitted by the Device instance that will call the listener function
listenerfunctionThe function that will be called the next time the specified event is emitted. The listener will be removed from the listeners array before being invoked.

See the Node.js Events Docs(link takes you to an external page) for more information.

device.rawListeners(eventName)

devicerawlistenerseventname page anchor

Returns an array of the listeners associated with the event named eventName. This includes any wrappers.

ParameterData TypeDescription
eventNamestring or symbolthe event for which you want to retrieve the listeners array (includes any wrappers)

See the Node.js Events Docs(link takes you to an external page) for more information.

Register the Device instance with Twilio, allowing it to receive incoming calls. This will open a signaling WebSocket, so the browser tab may show the 'recording' icon.

It's not necessary to call device.register() in order to make outgoing calls.


_10
const device = new Device(token);
_10
_10
const handleSuccessfulRegistration = () => {
_10
console.log('The device is ready to receive incoming calls.')
_10
}
_10
_10
device.on('registered', handleSuccessfulRegistration);
_10
_10
device.register();

(information)

Info

Some browsers will throw errors on pages that play audio that isn't initiated by a user gesture. Twilio recommends calling device.register() in response to a user gesture, such as a click. One popular and intuitive way to implement this is to add a button that will call device.register().

Example:

A user clicks on a Start Device button that will fire device.register() to enable the Device instance to receive incoming calls. Once registered, the Device instance will emit the 'registered' event.


_12
const device = new Device(token);
_12
_12
// Listen for the 'registered' event
_12
device.on('registered', () => {
_12
console.log('The device is ready to receive calls.')
_12
})
_12
_12
// A 'Start Device' button click calls this method
_12
const startDevice = () => {
_12
console.log('Registering the device to receive calls.');
_12
device.register();
_12
}

device.removeAllListeners(eventNames?)

deviceremovealllistenerseventnames page anchor

Removes all listeners on the Device instance if no argument is passed. This is not recommended.

The optional eventNames parameter is an array of event name strings.

If eventNames argument is passed, only those listeners will be removed. This is only recommended for events and event listeners that you have added, not those created by the SDK.


_10
const device = new Device(token);
_10
_10
// removes all event listeners
_10
device.removeListeners();
_10
_10
// removes the listeners for the "event1" and "event2" events
_10
device.removeListeners(["event1", "event2"]);

See the Node.js Events Docs(link takes you to an external page) for more information.

device.removeListener(eventName, listener)

deviceremovelistenereventname-listener page anchor

Removes the listener specified by the eventName and listener arguments. This is analogous to device.off().


_10
const device = new Device(token);
_10
_10
const handleSuccessfulRegistration = () => {
_10
console.log('The device is ready to receive incoming calls.')
_10
}
_10
_10
device.on('registered', handleSuccessfulRegistration);
_10
_10
device.removeListener('registered', handleSuccessfulRegistration);

See the Node.js Events Docs(link takes you to an external page) for more information.

device.setMaxListeners(number)

devicesetmaxlistenersnumber page anchor

Set the maximum number of event listeners allowed on this Device instance. The default maximum is 10.

Calling this method will change only the maximum allowed on this specific instance of a Device. If you want to change the maximum number of listeners allowed for all Device instances, consider setting the static Device.defaultMaxListeners property on the global Device object provided by the SDK.

Note: device.setMaxListeners(number) will have precedence over Device.defaultMaxListeners.


_10
const device = new Device(token);
_10
_10
device.setMaxListeners(20);

device.unregister()

deviceunregister page anchor

Unregister the Device instance with Twilio. This will prevent the Device instance from receiving incoming calls.

The Device instance will emit the 'unregistered' event when successfully unregistered with Twilio.


_11
const device = new Device(token);
_11
_11
// Listen for the 'unregistered' event
_11
device.on('unregistered', () => {
_11
console.log('The device is no longer able to receive calls.')
_11
})
_11
_11
const unregisterDevice = () => {
_11
console.log('Unregistering the device.');
_11
device.unregister();
_11
}

device.updateOptions(options)

deviceupdateoptionsoptions page anchor

Set the options used within the Device instance.

See the DeviceOptions section above for the full list of available options.

Example:

Specify an Edge location and custom sounds


_11
const options = {
_11
edge: 'ashburn',
_11
sounds: {
_11
incoming: '',
_11
outgoing: '',
_11
dtmf8: ''
_11
}
_11
}
_11
_11
const device = new Device(token);
_11
device.updateOptions(options);

device.updateToken(token)

deviceupdatetokentoken page anchor

Update the token used by this Device instance to connect to Twilio.

If the token expires, the Device instance will not be able to receive or make calls. It will also prevent statistics from being sent to Voice Insights.

It is recommended to call this API after device.tokenWillExpire event is emitted, and before or after a call to prevent a potential ~1s audio loss during the update process.

In the future, as Twilio explores signaling reconnection support, keeping this token updated will be important for automatically restoring connection to a Call or re-registering the Device instance.

Example:


_11
// time to live for the token, in milliseconds
_11
const timeToLive = 600000; // 10 minutes
_11
const refreshBuffer = 30000; // 30 seconds
_11
_11
const token = await getTokenViaAjax({ timeToLive });
_11
const device = new Device(token);
_11
_11
setInterval(async () => {
_11
const newToken = await getTokenViaAjax({ timeToLive });
_11
device.updateToken(token);
_11
}, timeToLive - refreshBuffer);


Emitted when the Device has been destroyed.

Listen for the 'destroyed' event.


_10
const device = new Device(token);
_10
_10
device.on('destroyed', () => {
_10
// Do something
_10
});

Emitted when the Device instance receives an error.

The event listener will receive a TwilioError and when applicable, a reference to the Call object that was active when the error occured. See the TwilioError section below for more information on the TwilioError object.

Listen for the 'error' event.


_10
const device = new Device(token);
_10
_10
device.on('error', (twilioError, call) => {
_10
console.log('An error has occurred: ', twilioError);
_10
});

TwilioError

The format of the TwilioError returned from the error event is a JavaScript object with the following properties:

PropertyDescription
causes string[]A list of possible causes for the error
code numberThe numerical code associated with this error
description stringA description of what the error means
explanation stringAn explanation of when the error may be observed
message stringAny further information discovered and passed along at runtime.
name stringThe name of this error
originalError (optional) stringThe original error received from the external system, if any
solutions string[]A list of potential solutions for the error

See a list of common errors on the Voice SDK Error Codes Page.

Emitted when an incoming Call is received. An event listener will receive the Call object representing the incoming Call.

Listen for the 'incoming' event.


_10
const device = new Device(token);
_10
_10
device.on('incoming', call => {
_10
// Do something
_10
});

Emitted when the Device instance is registered and able to receive incoming calls.

Listen for the 'registered' event.


_10
const device = new Device(token);
_10
_10
device.on('registered', () => {
_10
// Do something
_10
});

Emitted when the Device instance is registering with Twilio to receive incoming calls.

Listen for the 'registering' event.


_10
const device = new Device(token);
_10
_10
device.on('registering', () => {
_10
// Do something
_10
});

Emitted when the Device instance's AccessToken is about to expire.

Use the refreshTokenMs property on the DeviceOptions object to set a custom warning time. The default is 10 seconds (10000 milliseconds) prior to the AccessToken expiring.

Listen for the 'tokenWillExpire' event.

You can use this event along with device.updateToken() to automatically retrieve a new AccessToken and update the AccessToken on the Device instance, as shown in the example below:


_10
device.on('tokenWillExpire', () => {
_10
const token = getNewTokenViaAjax();
_10
device.updateToken(token);
_10
});

Emitted when the Device instance has unregistered with Twilio.

Listen for the 'unregistered' event.


_10
const device = new Device(token);
_10
_10
device.on('unregistered', () =>
_10
// Do something
_10
});


Return the AudioHelper(link takes you to an external page) object used by the Device instance. See the device.audio docs for more information.

Returns an array of Calls that this Device instance is maintaining.

Modifying one of these calls will have the same affect as modifying the same Call as it was returned by device.on('incoming') or device.connect().


_10
const device = new Device(token);
_10
_10
// make an ougoing call
_10
device.connect({ params: { To: "+15551234567" } });
_10
_10
console.log(device.calls);
_10
_10
// Prints:
_10
// []

Returns the Edge value the Device instance is currently connected to. The value will be null when the Device instance is offline.


_10
const device = new Device(token);
_10
_10
device.on("registered", () => {
_10
console.log(device.edge);
_10
});
_10
_10
device.register();
_10
_10
// Prints:
_10
// ashburn

Returns the home Twilio Region the Device instance is connected to as a string. The value will be null when the Device instance is offline.


_10
const device = new Device(token);
_10
_10
console.log(device.home);
_10
_10
// The default region for the JavaScript SDK is US-1
_10
_10
// Prints:
_10
// 'us1'

Returns the identity string that is associated with the Device instance's current AccessToken.

This accessor is only populated when the Device instance has successfully registered with Twilio.

Returns a Boolean for whether the Device instance is currently on an active Call


_16
const device = new Device(token);
_16
_16
console.log(device.isBusy);
_16
_16
// Prints:
_16
// false
_16
_16
_16
_16
// make an outgoing call
_16
device.connect({ params: { To: "+15551234567" });
_16
_16
console.log(device.isBusy);
_16
_16
// Prints:
_16
// true

Returns the state of the Device instance


_10
const device = new Device(token);
_10
_10
console.log(device.state);
_10
_10
// Prints:
_10
// unregistered

The possible Device instance states are:

  • unregistered - The Device instance is not registered with Twilio and cannot accept incoming calls
  • registering - The Device instance is registering with Twilio to accept incoming calls
  • registered - The Device instance is registered with Twilio and can accept incoming calls
  • destroyed - The Device instance has been destroyed and will not be able to make or receive new calls

Use event listeners on the Device instance to give the user feedback when the Device instance's state changes. See the Best Practices Page for more information.

Returns the token used by this Device instance


_10
const device = new Device(token);
_10
_10
console.log(device.token);
_10
_10
// Prints:
_10
// eyJhbGciOiJIUzI1NiIsInR5cCI6Ikp....

You can use the JWT debugger(link takes you to an external page) to decode and inspect the token.


Static methods should be called on the Device global object provided by the SDK.

Device.runPreflight(token, options?)

devicerunpreflighttoken-options page anchor

Returns a PreflightTest object representing a test call to Twilio which provides information to help troubleshoot call related issues.

Example:


_10
const preflightTest = Device.runPreflight(token, options);

A Twilio.PreflightTest object represents a test call to Twilio which provides information to help troubleshoot call related issues. You never instantiate it directly, but it's returned when you call Device.runPreflight(token, options).

See the PreflightTest Page for more information.


Static properties are those properties that only exist on the global Device object.

Device.defaultMaxListeners

devicedefaultmaxlisteners page anchor

Use this to change the default maximum number of event listeners permitted on all instances of a Device.


_10
Device.defaultMaxListeners = 20;

If you need to change the maximum number of event listeners on a specific Device instance, call the device.setMaxListeners(number) method on that instance.

Note: device.setMaxListeners(number) will have precedence over Device.defaultMaxListeners.


Static accessors should be called on the Device global provided by the SDK.

Returns a Boolean for whether or not this SDK is supported by the current browser


_10
console.log(Device.isSupported);
_10
_10
// Prints:
_10
// true

Returns the package name of the SDK


_10
console.log(Device.packageName);
_10
_10
// Prints:
_10
// @twilio/voice-sdk

Returns the current SDK version


_10
console.log(Device.version);
_10
_10
// Prints:
_10
// 2.0.0


Rate this page: