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). This will activate the device and give it an identity and certain privileges based on the token passed. 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().

The optional params argument is a JavaScript object where configuration settings can be passed in to .setup.

Property Default Description
rtc true Can be true or false. Set this property to false to force the use of Flash instead of WebRTC.
debug false Can be true or false. Set this property to true to enable debug logging in your browser console.
Twilio.Device.setup(token);

.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 network connection drops, meaning the device will not receive incoming connections.

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

.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 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 device.

The handler function receives a Twilio.Connection object as an argument. But the connection is already canceled so it won't be very useful.

.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] )

Attempt a new connection to a Twilio Application.

The optional params argument is a JavaScript object which will be url-encoded and 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.

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

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

Remember, outgoing connections from your device are made to the VoiceUrl of a Twilio Application within your account. You configure the Application you want to connect to using the Capability Token you provided in .setup(token). See the Client Quickstart on setting up an application for more information.
Example VoiceUrl TwiML

If your Twilio Application's VoiceUrl returns this:

<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(). But just as easily, your VoiceUrl could return:

<Response>
  <Say>There's a robot voice in your browser.</Say>
</Response>

or

<Response>
  <Dial>
    <Conference>MyWebConference</Conference>
  </Dial>
</Response>

to have your device connect to a conference. All of TwiML is available to you.

.disconnectAll()

Terminate all active connections. This will trigger the disconnect event handler for each active connection. 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 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 your client disconnects the offline event will fire, and when 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 asynchronous 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 occured.
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 can receive incoming connections and attempt outgoing connections.

"offline"

The device is not connected and cannot receive incoming connections.

"busy"

The device is connected to the network, has an active connection, and cannot receive incoming connections or make outgoing connection attempts.

Sounds Reference

.sounds

The configuration object for the sounds for this device. These are the default sounds played for an incomming 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. Calling this without a parameter returns the status of the incoming sound.

.sounds.outgoing( [bool] )

Enable or disable the outgoing event sound. Calling this without a parameter returns the status of the disconnect sound.

.sounds.disconnect( [bool] )

Enable or disable the disconnect event sound. Calling this without a parameter returns the status of the disconnect sound.

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.1/twilio.min.js">
</script>
<script type="text/javascript">
    // Set up with TOKEN, a string generated server-side
    Twilio.Device.setup("");

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