Get Started

The twilio.js Library: Twilio.Device

The Twilio.Device object is available when twilio.js is included in your page. It represents a soft device, the client that provides connections into Twilio. There is no need to instantiate Twilio.Device yourself, but you do need to invoke .setup() before using it.

Method Reference

The following is a list of methods available on Twilio.Device:

.setup( token, [params] )

Initialize Twilio.Device with a capability token (see Twilio Client Capability Tokens). The token you provide will activate the device, give it an identity, grant it privileges to make and receive inbound and/or outbound calls, and associate it with a specific Twilio application. You should call this before anything else. If your token allows inbound client connections, the device will start listening for new connections when you call .setup().

.setup()'s params argument takes a JavaScript object containing configuration settings. Available settings are listed below:

Property Default Description
rtc true Can be true or false. Set this property to false to force Flash instead of WebRTC.
debug false Can be true or false. Set this property to true to enable debug logging in your browser console.
simplePermissionDialog false Can be true or false. Set this property to true to use a simpler permissions prompt when using Flash. NOTE: When you use the simpler dialog, the browser will not remember the customer's previous selection. If the customer denies the initial permissions prompt, Twilio Client will revert to the standard Flash dialog until the browser has been reloaded.
closeProtection false Can be boolean or string. Setting this property to true will enable a dialog prompt with the text "A call is currently in progress. Leaving or reloading this page will end the call." when closing a page which has an active connection. Setting the property to a string will change the text of the message prompt. NOTE: Where custom text is not supported on the browser, Twilio will display the browser's default dialog.
warnings true Can be true or false. Set this property to false to disable logging to your browser console when calling deprecated methods.
audioConstraints true Can be true or MediaTrackConstraints. Set this property to select a specific microphone, or turn off features like auto-gain control, for the entire Twilio.Device. Each web browser implements a different set of MediaTrackConstraints, so consult your browser's implementation of getUserMedia for further details. This property can also be overridden for each Twilio.Connection.

For example:

Twilio.Device.setup(token); // use the default parameters

Or using params:

Twilio.Device.setup(token, { debug: true, rtc: false }); // enable debug logging and force Flash

.ready( handler(device) )

Register a handler function to be called when the ready event is fired. This is initially triggered when all operations in .setup() have completed and the device is ready and online. It may be triggered again if the device goes offline and comes back online (i.e. the connection drops and returns).

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

Twilio.Device.ready(function(device) {
  // The device is now ready
  console.log("Twilio.Device is now ready for connections");
});

.offline( handler(device) )

Register a handler function to be called when the offline event is fired. This is triggered when the connection to Twilio drops or the device's capability token is invalid/expired. In either of these scenarios, the device cannot receive incoming connections or make outgoing connections. If the token expires during an active connection the offline event handler will be called, but the connection will not be terminated. In this situation you will have to call Twilio.Device.setup() with a valid token before attempting or receiving the next connection.

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

We strongly recommend you implement an .offline() event handler before putting your application into production so that your application handles these scenarios gracefully.

.incoming( handler(connection) )

Register a handler function to be called when an incoming event is fired. This is triggered whenever an incoming connection from an outbound REST call or a TwiML <Dial> to this device is made.

Remember, to enable incoming connections you must give your device a name using the Capability Token you provided in .setup(token). See the Client Quickstart on receiving incoming connections for more information.

The handler function receives a Twilio.Connection object as an argument. This connection will be in state pending until you call .accept() on it.

Twilio.Device.incoming(function(connection) {
  connection.accept();
  // do awesome ui stuff here
  // $('#call-status').text("you're on a call!");
});

.cancel( handler(connection) )

Register a handler function to be called when the device receives a canceled event. This is triggered when an incoming connection is canceled by the caller before it is accepted by the Twilio Client device.

The handler function receives a Twilio.Connection object as an argument. Since this Connection object represents an inactive connection, you'll probably just want to use the event to update your application's UI, then throw away the Connection and wait for the next call.

.connect( handler(connection) )

Register a handler function to be called when the device receives a connect event. This is triggered when a connection is opened, whether initiated using .connect() or via an accepted incoming connection.

The handler function receives a Twilio.Connection object as an argument.

.connect( [params [, audioConstraints]] )

Attempts a new connection to the Twilio application that you associated with this Device's capability token when you called .setup() (see Twilio Client Capability Tokens for more information).

The optional params argument is a JavaScript object which will be passed to your application as POST/GET parameters.

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

For example, the following code will pass the params agent=Smith and location=Matrix to the Twilio application associated with this Device's capability token.

var connection = Twilio.Device.connect({
  agent: "Smith",
  location: "Matrix"
});

You can also 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.

var audioConstraints = {
  optional: [{ sourceId: 'XXX' }]
};

var connection = Twilio.Device.connect(null, audioConstraints);

The .connect() method returns a Twilio.Connection object. You can end the connection by calling its .disconnect() method.

Example VoiceUrl TwiML

When you call .connect(), the client will attempt a new connection to the Twilio Application you use in your Twilio.Device's capability token. This application can do whatever you like: Make a phone call to a phone number or Twilio Client address, start a conference call, interact with an IVR, etc.

For example, if your application's VoiceUrl returns the following TwiML:

<Response>
  <Dial callerId="+1888XXXXXXX">
    415-867-5309
  </Dial>
</Response>

then your device will make a call to 415-867-5309 every time you call .connect().

All of TwiML is available to your client applications.

You can use the params passed to the application in .connect() to dynamically generate the right TwiML for your app. For example, you could do the following in your JavaScript code:

var number = '5558675309';
var connection = Twilio.Device.connect({
  phone: number
});

And in the web application that generates your TwiML, retrieve the phone parameter from the HTTP request and insert into your TwiML as follows:

<Response>
  <Dial callerId="+1888XXXXXXX">
    5558675309
  </Dial>
</Response>

.activeConnection()

Returns the active connection object. Connection objects can be used to perform operations on the connection like mute, unmute, sending DTMF digits, etc.

.disconnectAll()

Terminates the active connection. This will trigger the disconnect event handler. It will not prevent new incoming connections.

.disconnect( handler(connection) )

Register a handler function to be called any time a connection is closed. The handler function receives the Twilio.Connection object that was just closed as an argument.

.presence( handler(PresenceEvent) )

Register a handler function to be called when the availability state changes for any client currently associated with your Twilio account. When the device is ready, this handler function is invoked once for each available client. Thereafter it is invoked as clients become available or unavailable.

A client is considered available even if another call is in progress.

Remember, when the Twilio.Device disconnects, the offline event will fire, and if it reconnects the presence handler function will be called again for every available online client.

The handler function receives a PresenceEvent object as an argument. The PresenceEvent object includes the following properties:

Property Description
from The string representing the registered client identifier for which the presence change has occurred. The string will only contain alphanumeric and underscore characters.
available true if the client specified by from is connected to Twilio, false otherwise.
Twilio.Device.presence(function(presenceEvent) {
  console.log("Presence Event: " + presenceEvent.from + " " + presenceEvent.available);
});

.error( handler(error) )

Register a handler function to be called when any device error occurs. 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:

Property Description
message A string describing the error.
code A numeric error code described in the Twilio Client error code reference.
info A copy of the Flash info object produced by the events around the flash.net.NetConnection object.
connection A reference to the Twilio.Connection object that was active when the error occurred.
Twilio.Device.error(function(error) {
  console.log(error.message);
});

.status()

Return the status of the device. The status will be one of the following strings: "offline", "ready", or "busy".

"ready"

The device is currently connected to Twilio and has a valid capability token.

"offline"

The device is either not connected to Twilio or has an expired/invalid capability token.

"busy"

The device is connected to Twilio, has an active connection, and cannot receive incoming connections or attempt outgoing connections.

.getMediaEngine()

Return the media engine used by the device. The media engine will be either Twilio.Device.getMediaEngine.WEBRTC or Twilio.Device.getMediaEngine.FLASH. You can check them as follows:

var mediaEngine = Twilio.Device.getMediaEngine();
switch (mediaEngine) {
  case Twilio.Device.getMediaEngine.WEBRTC:
    // Do something if WebRTC is enabled.
    break;
  case Twilio.Device.getMediaEngine.FLASH:
    // Do something if Flash is enabled.
    break;
}

Sounds Reference

.sounds

The configuration object for the sounds for this device. These are the default sounds played for an incoming connection, initiating an outgoing connection, and disconnecting a connection. The following functions are available on this property.

.sounds.incoming( [bool] )

Enable or disable the incoming event sound.

.sounds.incoming()

Returns a boolean indicating whether the incoming sound is enabled or disabled.

.sounds.outgoing( [bool] )

Enable or disable the outgoing event sound.

.sounds.outgoing()

Returns a boolean indicating whether the outgoing sound is enabled or disabled.

.sounds.disconnect( [bool] )

Enable or disable the disconnect event sound.

.sounds.disconnect()

Returns a boolean indicating whether the disconnect sound is enabled or disabled.

Example Code

<script type="text/javascript"
        src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<script type="text/javascript"
        src="//static.twilio.com/libs/twiliojs/1.2/twilio.min.js">
</script>
<script type="text/javascript">
    // Set up with TOKEN, a string generated server-side
    Twilio.Device.setup("{TOKEN}");

    Twilio.Device.ready(function() {
        // Could be called multiple times if network drops and comes back.
        // When the TOKEN allows incoming connections, this is called when
        // the incoming channel is open.
    });

    Twilio.Device.offline(function() {
        // Called on network connection lost.
    });

    Twilio.Device.incoming(function(conn) {
        console.log(conn.parameters.From); // who is calling
        conn.status // => "pending"
        conn.accept();
        conn.status // => "connecting"
    });

    Twilio.Device.cancel(function(conn) {
        console.log(conn.parameters.From); // who canceled the call
        conn.status // => "closed"
    });

    Twilio.Device.connect(function (conn) {
        // Called for all new connections
        console.log(conn.status);
    });

    Twilio.Device.disconnect(function (conn) {
        // Called for all disconnections
        console.log(conn.status);
    });

    Twilio.Device.presence(function (presenceEvent) {
        // Called for each available client when this device becomes ready
        // and every time another client's availability changes.
        presenceEvent.from // => name of client whose availability changed
        presenceEvent.available // => true or false
    });

    Twilio.Device.error(function (e) {
        console.log(e.message + " for " + e.connection);
    });

    $(document).ready(function () {
        Twilio.Device.connect({
            agent: "Smith",
            phone_number: "4158675309"
        });
    });

    $("#hangup").click(function() {
        Twilio.Device.disconnectAll();
    });
</script>