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

TaskRouter.js v1 Worker: Managing workers in the browser


Want to learn how to use TaskRouter.js Worker to route tasks to a web-based application? Dive into the TaskRouter Quickstart.

TaskRouter's JavaScript SDK makes it easy to build web-based applications for the people that will process TaskRouter Tasks. The SDK allows developers to:

  • Register an endpoint as a TaskRouter Worker.
  • Manage the registered Worker's Activity state.
  • Receive assigned Task & Reservation details.
  • Accept & Reject Reservations.
  • Call a given Worker with a Dequeue or Call instruction

  • _10
    Complete Tasks


How does it work?

how-does-it-work page anchor

The TaskRouter JavaScript SDK makes a WebSocket connection to TaskRouter. TaskRouter events and commands, such as Task Assignment and Acceptance, or Activity changes, are communicated via this Websocket connection.


Adding the SDK to your application

adding-the-sdk-to-your-application page anchor

Include the TaskRouter JS SDK in your JavaScript application as follows:


_10
<script src="https://sdk.twilio.com/js/taskrouter/v1.21/taskrouter.min.js" integrity="sha384-5fq+0qjayReAreRyHy38VpD3Gr9R2OYIzonwIkoGI4M9dhfKW6RWeRnZjfwSrpN8" crossorigin="anonymous"></script>

Creating a TaskRouter Worker capability token

capability-token page anchor

TaskRouter uses Twilio capability tokens to delegate scoped access to TaskRouter resources to your JavaScript application. Twilio capability tokens conform to the JSON Web Token (commonly referred to as a JWT and pronounced "jot") standard, which allow for limited-time use of credentials by a third party. Your web server needs to generate a Twilio capability token and provide it to your JavaScript application in order to register a TaskRouter worker.

There are two capabilities you can enable today (and in most cases you'll want to use all of them in your application):

CapabilityAuthorization
ActivityUpdatesA worker can update its current Activity.
ReservationUpdatesA worker can accept or reject a reservation as well as provide a dequeue or call instruction.

You can generate a TaskRouter capability token using any of Twilio's Helper Libraries. You'll need to provide your Twilio AccountSid and AuthToken, along with the WorkspaceSid and WorkerSid for the Worker you would like to register. For example, using our PHP helper library you can create a token and add capabilities as follows:

Creating a TaskRouter Worker capability token

creating-a-taskrouter-worker-capability-token page anchor
Node.js
Python
C#
Java
PHP
Ruby

_58
// Download the Node helper library from twilio.com/docs/node/install
_58
// These consts are your accountSid and authToken from https://www.twilio.com/console
_58
const taskrouter = require('twilio').jwt.taskrouter;
_58
const util = taskrouter.util;
_58
_58
const TaskRouterCapability = taskrouter.TaskRouterCapability;
_58
const Policy = TaskRouterCapability.Policy;
_58
_58
// To set up environmental variables, see http://twil.io/secure
_58
const accountSid = process.env.TWILIO_ACCOUNT_SID;
_58
const authToken = process.env.TWILIO_AUTH_TOKEN;
_58
const workspaceSid = 'WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
_58
const workerSid = 'WKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
_58
_58
const TASKROUTER_BASE_URL = 'https://taskrouter.twilio.com';
_58
const version = 'v1';
_58
_58
const capability = new TaskRouterCapability({
_58
accountSid: accountSid,
_58
authToken: authToken,
_58
workspaceSid: workspaceSid,
_58
channelId: workerSid});
_58
_58
// Helper function to create Policy
_58
function buildWorkspacePolicy(options) {
_58
options = options || {};
_58
var resources = options.resources || [];
_58
var urlComponents = [TASKROUTER_BASE_URL, version, 'Workspaces', workspaceSid]
_58
_58
return new Policy({
_58
url: urlComponents.concat(resources).join('/'),
_58
method: options.method || 'GET',
_58
allow: true
_58
});
_58
}
_58
_58
// Event Bridge Policies
_58
const eventBridgePolicies = util.defaultEventBridgePolicies(accountSid, workerSid);
_58
_58
// Worker Policies
_58
const workerPolicies = util.defaultWorkerPolicies(version, workspaceSid, workerSid);
_58
_58
const workspacePolicies = [
_58
// Workspace fetch Policy
_58
buildWorkspacePolicy(),
_58
// Workspace subresources fetch Policy
_58
buildWorkspacePolicy({ resources: ['**'] }),
_58
// Workspace Activities Update Policy
_58
buildWorkspacePolicy({ resources: ['Activities'], method: 'POST' }),
_58
// Workspace Activities Worker Reserations Policy
_58
buildWorkspacePolicy({ resources: ['Workers', workerSid, 'Reservations', '**'], method: 'POST' }),
_58
];
_58
_58
eventBridgePolicies.concat(workerPolicies).concat(workspacePolicies).forEach(function (policy) {
_58
capability.addPolicy(policy);
_58
});
_58
_58
const token = capability.toJwt();

Additionally, you can to define more granular access to particular resources beyond these capabilities. These can be viewed under Constructing JWTs.

Once you have generated a TaskRouter capability token, you can pass this to your front-end web application and intialize the JavaScript library as follows:


_10
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);

The library will raise a 'ready' event once it has connected to TaskRouter:


_10
worker.on("ready", function(worker) {
_10
console.log(worker.sid) // 'WKxxx'
_10
console.log(worker.friendlyName) // 'Worker 1'
_10
console.log(worker.activityName) // 'Reserved'
_10
console.log(worker.available) // false
_10
});

See more about the methods and events exposed on this object below.


TaskRouter.js Worker exposes the following API:


Twilio.TaskRouter.Worker

taskrouterworker page anchor

Twilio.TaskRouter.Worker is the top-level class you'll use for managing a Worker's activity, and receiving notifications when a Worker is assigned a task or when a Worker's Activity is changed.

new Twilio.TaskRouter.Worker(workerToken)

new-taskrouterworker page anchor

Register a new Twilio.TaskRouter.Worker with the capabilities provided in workerToken.

NameTypeDescription
workerTokenStringA Twilio TaskRouter capability token. See Creating a TaskRouter capability token for more information.
debugBoolean(optional) Whether or not the JS SDK will print event messages to the console. Defaults to true.
connectActivitySidString(optional) ActivitySid to place the worker in upon the WebSocket Connecting
disconnectActivitySidString(optional) ActivitySid to place the worker in upon the Websocket Disconnecting
closeExistingSessionsBoolean(optional) Whether or not to disconnect existing websockets for the same Worker upon Connecting. Defaults to false.
regionString(optional) A Twilio region for websocket connections (ex. ie1-ix).
maxRetriesInteger(optional) The maximum of retries to attempt if a websocket request fails. Defaults to 0.

_10
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);

Turning off debugging:


_10
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN, false);

Adding Connecting and Disconnecting Activities, and closing Existing Sessions


_10
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN, false, "WAxxx", "WAyyy", true);

update([args...], [resultCallback])

update page anchor

Updates properties of a Worker. There are properties of a Worker, such as ActiveSid, FriendlyName, etc. These can be edited singly (see below) or in bulk. If you wish to change the Attributes property of a Worker, you must pass in the full JSON blob of its new Attributes.

To update the activity or reservation of a specific worker, please refer to the Worker Resource.

Note: Updating the activity or reservation If updating the Worker's activity state, the activity.update event will also fire. If updating the Worker's attributes, the attributes.update event will also fire.

Parameters
parameters-2 page anchor
NameTypeDescription
args...String or JSONA single API parameter and value or a JSON object containing multiple values
resultCallbackFunction(optional) A JavaScript Function that will be called with the result of the update. If an error occurs, the first argument passed to this function will be an Error. If the update is successful, the first argument will be null and the second argument will contain the updated Worker object.
Single Attribute Example
single-attribute-example page anchor

_10
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);
_10
_10
worker.update("ActivitySid", "WAxxx", function(error, worker) {
_10
if(error) {
_10
console.log(error.code);
_10
console.log(error.message);
_10
} else {
_10
console.log(worker.activityName); // "Offline"
_10
}
_10
});

Multiple Attribute Example
multiple-attribute-example page anchor

_12
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);
_12
_12
const props = {"ActivitySid":"WAxxx", "FriendlyName":"UpdatedWorker"};
_12
_12
worker.update(props, function(error, worker) {
_12
if(error) {
_12
console.log(error.code);
_12
console.log(error.message);
_12
} else {
_12
console.log(worker.activityName); // "Offline"
_12
}
_12
});

updateToken(workerToken)

updatetoken page anchor

Updates the TaskRouter capability token for the Worker.

NameTypeDescription
workerTokenStringA valid TaskRouter capability token.

_10
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);
_10
_10
const token = refreshJWT(); // your method to retrieve a new capability token
_10
worker.updateToken(token);

activities.fetch(callback)

fetchactivities page anchor

Retrieves the list of Activities configured in your TaskRouter's Workspace.

NameTypeDescription
callbackFunctionA function that will be called when the Activity list is returned. If an error occurs when retrieving the list, the first parameter passed to this function will contain the Error object. If the retrieval is successful, the first parameter will be null and the second parameter will contain an Array of Activities

_15
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);
_15
_15
worker.activities.fetch(
_15
function(error, activityList) {
_15
if(error) {
_15
console.log(error.code);
_15
console.log(error.message);
_15
return;
_15
}
_15
const data = activityList.data;
_15
for(i=0; i<data.length; i++) {
_15
console.log(data[i].friendlyName);
_15
}
_15
}
_15
);

fetchReservations(callback)

fetchreservations page anchor

Retrieves the list of Reservations assigned to your Worker

NameTypeDescription
callbackFunctionA function that will be called when the Reservation list is returned. If an error occurs when retrieving the list, the first parameter passed to this function will contain the Error object. If the retrieval is successful, the first parameter will be null and the second parameter will contain an Array of Reservations
paramsObject(optional) A JSON object of query parameters

_15
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);
_15
_15
worker.fetchReservations(
_15
function(error, reservations) {
_15
if(error) {
_15
console.log(error.code);
_15
console.log(error.message);
_15
return;
_15
}
_15
const data = reservations.data;
_15
for(i=0; i<data.length; i++) {
_15
console.log(data[i].sid);
_15
}
_15
}
_15
);

The following will fetch just pending reservations:


_18
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);
_18
_18
const queryParams = {"ReservationStatus":"pending"};
_18
_18
worker.fetchReservations(
_18
function(error, reservations) {
_18
if(error) {
_18
console.log(error.code);
_18
console.log(error.message);
_18
return;
_18
}
_18
const data = reservations.data;
_18
for(i=0; i<data.length; i++) {
_18
console.log(data[i].sid);
_18
}
_18
},
_18
queryParams
_18
);

fetchChannels(callback)

fetchchannels page anchor

Retrieves the list of Channels assigned to your Worker

Note: To utilize this, when constructing your Worker JWT, allow your worker to fetch subresources of the given Worker.

NameTypeDescription
callbackFunctionA function that will be called when the Worker Channel list is returned. If an error occurs when retrieving the list, the first parameter passed to this function will contain the Error object. If the retrieval is successful, the first parameter will be null and the second parameter will contain an Array of Channels

_15
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);
_15
_15
worker.fetchChannels(
_15
function(error, channels) {
_15
if(error) {
_15
console.log(error.code);
_15
console.log(error.message);
_15
return;
_15
}
_15
const data = channels.data;
_15
for(i=0; i<data.length; i++) {
_15
console.log(data[i].taskChannelUniqueName + " with capacity: " + data[i].configuredCapacity);
_15
}
_15
}
_15
);

updateTask(taskSid, params, callback)

updatetask page anchor

Updates a given Task with the given parameters

NameTypeDescription
taskSidStringThe given TaskSid
paramsJSONJSON object containing multiple values
callbackFunctionA function that will be called when the updated instance is returned. If an error occurs when updating the instance, the first parameter passed to this function will contain the Error object. If the update is successful, the first parameter will be null and the second parameter will contain the updated instance.

_13
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);
_13
_13
const params = {"Priority":"15"};
_13
worker.updateTask(taskSid, params,
_13
function(error, updatedTask) {
_13
if(error) {
_13
console.log(error.code);
_13
console.log(error.message);
_13
return;
_13
}
_13
console.log("Updated Task Priority: "+updatedTask.priority);
_13
}
_13
);

completeTask(taskSid, callback, reason)

completetask page anchor

Completes a given Task with an optional reason

NameTypeDescription
taskSidStringThe given TaskSid
callbackFunctionA function that will be called when the updated instance is returned. If an error occurs when updating the instance, the first parameter passed to this function will contain the Error object. If the update is successful, the first parameter will be null and the second parameter will contain the updated instance.
reasonString(optional) The reason for completion

_12
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);
_12
_12
worker.completeTask(taskSid,
_12
function(error, completedTask) {
_12
if(error) {
_12
console.log(error.code);
_12
console.log(error.message);
_12
return;
_12
}
_12
console.log("Completed Task: "+completedTask.assignmentStatus);
_12
}
_12
);

If you have the context of given Reservation, you can complete Task from the Task object itself:

NameTypeDescription
callbackFunction(optional) A function that will be called when the updated instance is returned. If an error occurs when updating the instance, the first parameter passed to this function will contain the Error object. If the update is successful, the first parameter will be null and the second parameter will contain the updated instance.
reasonString(optional) The reason for completion

_10
reservation.task.complete();

With the optional callback, this would look like the following:


_10
reservation.task.complete(
_10
function(error, completedTask) {
_10
if(error) {
_10
console.log(error.code);
_10
console.log(error.message);
_10
return;
_10
}
_10
console.log("Completed Task: "+completedTask.assignmentStatus);
_10
}
_10
);

on(event, callback)

worker-on page anchor

Attaches a listener to the specified event. See Events for the complete list of supported events.

NameTypeDescription
eventStringAn event name. See Events for the complete list of supported events.
callbackFunctionA function that will be called when the specified Event is raised.

_10
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);
_10
_10
worker.on("activity.update", function(worker) {
_10
console.log(worker.activityName) // 'Reserved'
_10
console.log(worker.activitySid) // 'WAxxx'
_10
console.log(worker.available) // false
_10
});


TaskRouter's JS library currently raises the following events to the registered Worker object:

The Worker has established a connection to TaskRouter and has completed initialization.

NameTypeDescription
workerWorkerThe Worker object for the Worker you've created.

_10
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);
_10
_10
worker.on("ready", function(worker) {
_10
console.log(worker.available) // true
_10
});

The Worker's activity has changed. This event is fired any time the Worker's Activity changes, both when TaskRouter updates a Worker's Activity, and when you make a change to the Worker's Activity via Worker.js or the TaskRouter REST API.

NameTypeDescription
workerWorkerThe updated Worker object

_10
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);
_10
_10
worker.on("activity.update", function(worker) {
_10
console.log(worker.sid) // 'WKxxx'
_10
console.log(worker.friendlyName) // 'Worker 1'
_10
console.log(worker.activityName) // 'Reserved'
_10
console.log(worker.available) // false
_10
});

The Worker's attributes have been updated.

NameTypeDescription
workerWorkerThe updated Worker object

_10
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);
_10
_10
worker.on("attributes.update", function(worker) {
_10
console.log(worker.sid) // 'WKxxx'
_10
console.log(worker.friendlyName) // 'Worker 1'
_10
console.log(worker.activityName) // 'Reserved'
_10
console.log(worker.available) // false
_10
});

The Worker's Capacity have been updated.

NameTypeDescription
channelWorkerChannelThe updated WorkerChannel object

_10
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);
_10
_10
worker.on("capacity.update", function(channel) {
_10
console.log(channel.sid) // 'WCxxx'
_10
console.log(channel.taskChannelUniqueName) // 'ipm'
_10
console.log(channel.available) // true
_10
console.log(channel.configuredCapacity) // '3'
_10
console.log(channel.availableCapacityPercentage) // 66.7
_10
console.log(channel.assignedTasks) // 2
_10
});

The Worker has been assigned a reservation.

NameTypeDescription
reservationReservationThe Reservation object that has been assigned to the Worker.

Access Task and their attributes details as you would with any other JavaScript object.


_10
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);
_10
_10
worker.on("reservation.created", function(reservation) {
_10
console.log(reservation.task.attributes) // {foo: 'bar', baz: 'bang' }
_10
console.log(reservation.task.priority) // 1
_10
console.log(reservation.task.age) // 300
_10
console.log(reservation.task.sid) // WTxxx
_10
console.log(reservation.sid) // WRxxx
_10
});

Raised when the Worker has accepted a Reservation.

NameTypeDescription
reservationReservationThe Reservation object that has been accepted for this worker.

_10
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);
_10
_10
worker.on("reservation.accepted", function(reservation) {
_10
console.log(reservation.task.attributes) // {foo: 'bar', baz: 'bang' }
_10
console.log(reservation.task.priority) // 1
_10
console.log(reservation.task.age) // 300
_10
console.log(reservation.task.sid) // WTxxx
_10
console.log(reservation.sid) // WRxxx
_10
});

Raised when the Worker has rejected a Reservation

NameTypeDescription
reservationReservationThe Reservation object that has been rejected for this worker.

_10
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);
_10
_10
worker.on("reservation.rejected", function(reservation) {
_10
console.log(reservation.task.attributes) // {foo: 'bar', baz: 'bang' }
_10
console.log(reservation.task.priority) // 1
_10
console.log(reservation.task.age) // 300
_10
console.log(reservation.task.sid) // WTxxx
_10
console.log(reservation.sid) // WRxxx
_10
});

Raised when a pending Reservation associated with this Worker times out.

NameTypeDescription
reservationReservationThe Reservation object that has been timed-out for this worker.

_10
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);
_10
_10
worker.on("reservation.timeout", function(reservation) {
_10
console.log(reservation.task.attributes) // {foo: 'bar', baz: 'bang' }
_10
console.log(reservation.task.priority) // 1
_10
console.log(reservation.task.age) // 300
_10
console.log(reservation.task.sid) // WTxxx
_10
console.log(reservation.sid) // WRxxx
_10
});

Raised when a pending Reservation associated with this Worker is canceled.

NameTypeDescription
reservationReservationThe Reservation object that has been canceled for this worker.

Handling reservation being canceled

handling-reservation-being-canceled page anchor

_10
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);
_10
_10
worker.on("reservation.canceled", function(reservation) {
_10
console.log(reservation.task.attributes) // {foo: 'bar', baz: 'bang' }
_10
console.log(reservation.task.priority) // 1
_10
console.log(reservation.task.age) // 300
_10
console.log(reservation.task.sid) // WTxxx
_10
console.log(reservation.sid) // WRxxx
_10
});

Raised when a pending Reservation associated with this Worker is rescinded in the case of multi-reservation.

NameTypeDescription
reservationReservationThe Reservation object that has been rescinded for this worker.

Handling reservation being rescinded

handling-reservation-being-rescinded page anchor

_10
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);
_10
_10
worker.on("reservation.rescinded", function(reservation) {
_10
console.log(reservation.task.attributes) // {foo: 'bar', baz: 'bang' }
_10
console.log(reservation.task.priority) // 1
_10
console.log(reservation.task.age) // 300
_10
console.log(reservation.task.sid) // WTxxx
_10
console.log(reservation.sid) // WRxxx
_10
});

Raised when the TaskRouter capability token used to create this Worker expires.


_10
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);
_10
_10
worker.on("token.expired", function() {
_10
console.log("updating token");
_10
const token = refreshJWT(); // your method to retrieve a new capability token
_10
worker.updateToken(token);
_10
});

Raised when the Websocket connects.


_10
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);
_10
_10
worker.on("connected", function() {
_10
console.log("Websocket has connected");
_10
});

Raised when the Websocket disconnects.


_10
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);
_10
_10
worker.on("disconnected", function() {
_10
console.log("Websocket has disconnected");
_10
});

Raised when the Websocket has an error.


_10
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);
_10
_10
worker.on("error", function(error) {
_10
console.log("Websocket had an error: "+ error.response + " with message: "+error.message);
_10
});


When a Worker receives a reservation.created event with a Reservation object, the reservation object contains several actionable methods on the reservation.

This will accept the reservation for the worker.

Note: This will NOT perform any telephony. If the task was enqueued using the Enqueue TwiML verb, utilize reservation.dequeue(#reservation-dequeue) to perform telephony and dequeue the call.

NameTypeDescription
resultCallbackFunction(optional) A JavaScript Function that will be called with the result of accepting the reservation. If an error occurs, the first argument passed to this function will be an Error. If the update is successful, the first argument will be null and the second argument will contain the updated Reservation object.

_13
reservation.accept(
_13
function(error, reservation) {
_13
if(error) {
_13
console.log(error.code);
_13
console.log(error.message);
_13
return;
_13
}
_13
console.log("reservation accepted");
_13
for (const property in reservation) {
_13
console.log(property+" : "+reservation[property]);
_13
}
_13
}
_13
);

If you do not care about the callback, then simply the following will do:


_10
reservation.accept();

This will reject the reservation for the worker.

NameTypeDescription
activitySidString(optional) The activitySid to update the worker to after rejecting the reservation
resultCallbackFunction(optional) A JavaScript Function that will be called with the result of rejecting the reservation. If an error occurs, the first argument passed to this function will be an Error. If the update is successful, the first argument will be null and the second argument will contain the updated Reservation object.

_13
reservation.reject(
_13
function(error, reservation) {
_13
if(error) {
_13
console.log(error.code);
_13
console.log(error.message);
_13
return;
_13
}
_13
console.log("reservation rejected");
_13
for (const property in reservation) {
_13
console.log(property+" : "+reservation[property]);
_13
}
_13
}
_13
);

If you do not care about the callback, then simply the following will do:


_10
reservation.reject();

If you do not care about the callback, but want to update the worker's ActivitySid then simply the following will do:


_10
reservation.reject("WAxxx");

This will create a conference and puts worker and caller into conference.

Note: This will create a conference for a task that was enqueued using the Enqueue TwiML verb.

NameTypeDescription
fromString(optional) The caller id for the call to the worker. This needs to be a verified Twilio number. If you need this to be the original callee number, please contact Support. If the "from" is not provided and the Task was created using Enqueue verb, then we will use the "To" number dialed by the caller as the "from" number when executing "conference" instruction.
postWorkActivitySidString(optional) The activitySid to update the worker to after conference completes.
timeoutstring(optional) The integer number of seconds that Twilio should allow the phone associated with "contact_uri" to ring before assuming there is no answer. Default is 60 seconds, the maximum is 999 seconds. Note, you could set this to a low value, such as 15, to hangup before reaching an answering machine or voicemail.
tostring(optional) The contact URI of the Worker. A phone number or client ID. Required if the worker's attributes do not include a "contact_uri" property.
resultCallbackFunction(optional) A JavaScript Function that will be called upon the completion of the dial. If an error occurs, the first argument passed to this function will be an Error. If the call is successful, the first argument will be null and the second argument will contain the non-updated Reservation object. However, you can still utilize actions on it. See below.
optionsobject(optional) If you have Agent Conference enabled, you can utilize similar parameters as specified by the Participants API for the Worker Conference Leg. See the documentation for the full list of parameters that can be used. You can enable Agent Conference via the Twilio Console
options.ConferenceStatusCallbackEventString[](optional) Ensure that, for the TaskRouter SDK, this parameter is a comma separated array. Refer to the documentation for the full list of values that can be included in the array.

If you simply wish to conference the call, then simply do the following since all parameters are optional:


_10
reservation.conference();

If you wish to hook into additional options, you can do so as follows:


_14
reservation.conference(
_14
"18004746453",
_14
"WAxxx",
_14
"30",
_14
"client:joey",
_14
function(error, reservation) {
_14
if(error) {
_14
console.log(error.code);
_14
console.log(error.message);
_14
return;
_14
}
_14
console.log("conference initiated");
_14
}
_14
);

If you wish to hook into Agent Conference parameters for the Worker Conference Leg, you can do so as follows:


_10
const options = {
_10
"ConferenceStatusCallback": "https://requestb.in/wzfljiwz",
_10
"ConferenceStatusCallbackEvent": "start,end",
_10
"ConferenceRecord": "true",
_10
"ConferenceRecordingStatusCallback": "https://requestb.in/wzfljiwz",
_10
"EndConferenceOnExit": "true"
_10
}
_10
_10
reservation.conference(null, null, null, null, null, options);

If you wish to NOT utilize Agent Conference or its parameters for the Worker Conference Leg, but control your conference settings via the options parameter, that is possible as well:


_11
const options = {
_11
"From": "18004746453",
_11
"PostWorkActivitySid": "WAxxx",
_11
"Timeout": "30",
_11
"To": "client:joey",
_11
"Record":"true",
_11
"ConferenceStatusCallback": "https://requestb.in/wzfljiwz",
_11
"ConferenceStatusCallbackEvent": "start,end,join,leave"
_11
}
_11
_11
reservation.conference(null, null, null, null, null, options);

This will dequeue the reservation for the worker.

Note: This will perform telephony to dequeue a task that was enqueued using the Enqueue TwiML verb.

Note: A Worker's Attributes must contain a contact_uri attribute for the call to go through since this will be considered the To for the Calls API.

NameTypeDescription
dequeueFromString(optional) The caller id for the call to the worker. This needs to be a verified Twilio number. If you need this to be the original callee number, please contact Support. If the "dequeueFrom" is not provided and the Task was created using Enqueue verb, then we will use the "To" number dialed by the caller as the "dequeueFrom" number when executing "dequeue" instruction.
dequeuePostWorkActivitySidString(optional) The activitySid to update the worker to after dequeuing the reservation
dequeueRecordstring(optional) The 'record' attribute lets you record both legs of a call. Set to "record-from-answer" to record the call from answer. Default to "do-not-record" which will not record the call. The RecordingUrl will be sent with status_callback_url.
dequeueTimeoutstring(optional) The integer number of seconds that Twilio should allow the phone associated with "contact_uri" to ring before assuming there is no answer. Default is 60 seconds, the maximum is 999 seconds. Note, you could set this to a low value, such as 15, to hangup before reaching an answering machine or voicemail.
dequeueStatusCallbackUrlstring(optional) A URL that Twilio will send asynchronous webhook requests to on completed call event. **Note: TaskRouter sends "taskCallSid" as parameter with sid of the call that created the Task. This is very useful in the event a call to worker fails, where you could remove the original call from queue and send to voice mail or enqueue again with new workflow to route to different group of workers.
dequeueStatusCallbackEventsstring(optional) Defines which Call Progress Events are sent to the above dequeueStatusCallbackUrl. By default, we will send only the call completed event. If you wish to listen to all, simply provide "initiated,ringing,answered,completed". Any permutation of the above as long as it is comma delimited is acceptable.
dequeueTostring(optional) The contact URI of the Worker. A phone number or client ID. Required if the worker's attributes do not include a "contact_uri" property.
resultCallbackFunction(optional) A JavaScript Function that will be called with the result of dequeuing the reservation. If an error occurs, the first argument passed to this function will be an Error. If the update is successful, the first argument will be null and the second argument will contain the updated Reservation object.

If you simply wish to dequeue the call, then simply the following will do since all parameters are optional:


_10
reservation.dequeue();

If you wish to hook into additional options, you can do so as follows:


_16
reservation.dequeue(
_16
"18004746453",
_16
"WAxxx",
_16
"record-from-answer",
_16
"30",
_16
"http://requestb.in/13285vq1",
_16
"client:joey",
_16
function(error, reservation) {
_16
if(error) {
_16
console.log(error.code);
_16
console.log(error.message);
_16
return;
_16
}
_16
console.log("reservation dequeued");
_16
}
_16
);

This will call a worker using the Twilio Calls API. To give a sense of the matchup of parameters, an additional column is listed on the parameters to indicate which Calls API parameter each JS SDK parameter is mapping to.

Note: If CallTo is not provided, a Worker's Attributes must contain a contact_uri attribute for the call to go through since this will be considered the To for the Calls API.

NameTypeDescriptionCalls API Parameter
callFromStringThe caller id for the call to the workerFrom
callUrlStringA valid TwiML URI that is executed on the answering Worker's leg.Url
callStatusCallbackUrlString(optional) A valid status callback url.StatusCallback
callAcceptString(optional) "true" or "false", accept the task before initiating call. Defaults to "false". Needs to be a string. Eg: "true", not true
callRecordString(optional) record-from-answer or false. Record the call. Defaults to false.Record
callToString(optional) Whom to call. If not provided, will utilize worker contact_uri attributeTo
resultCallbackFunction(optional) A JavaScript Function that will be called upon the completion of the dial. If an error occurs, the first argument passed to this function will be an Error. If the call is successful, the first argument will be null and the second argument will contain the non-updated Reservation object. However, you can still utilize actions on it. See below.

_16
reservation.call(
_16
"18004746453",
_16
"http://twimlbin.com/451369ae",
_16
"http://requestb.in/13285vq1",
_16
"true",
_16
"record-from-answer",
_16
"client:joey"
_16
function(error, reservation) {
_16
if(error) {
_16
console.log(error.code);
_16
console.log(error.message);
_16
return;
_16
}
_16
console.log("reservation called the worker");
_16
}
_16
);

If you do not care about the callback, then simply the following will do:


_10
reservation.call(
_10
"18004746453",
_10
"http://twimlbin.com/451369ae",
_10
"http://requestb.in/13285vq1",
_10
"false");

If you do not care about the status callback, and want to accept the reservation AFTER the call is bridged, you can do the following:


_16
reservation.call(
_16
"18004746453",
_16
"http://twimlbin.com/451369ae",
_16
null,
_16
null,
_16
null,
_16
null,
_16
function(error, reservation) {
_16
if(error) {
_16
console.log(error.code);
_16
console.log(error.message);
_16
return;
_16
}
_16
reservation.accept();
_16
}
_16
);

If you do not care about the callback, or the status callback, and want to accept the reservation BEFORE the call is bridged, you can do the following:


_10
reservation.call(
_10
"18004746453",
_10
"http://twimlbin.com/451369ae",
_10
null,
_10
"true");

This will redirect the active call tied to a reservation using the Twilio Calls API. To give a sense of the matchup of parameters, an additional column is listed on the parameters to indicate which Calls API parameter each JS SDK parameter is mapping to.

NameTypeDescriptionCalls API Parameter
redirectCallSidStringThe Call to RedirectFrom
redirectUrlStringA valid TwiML URI that is executed on the Caller's leg upon redirecting.Url
redirectAcceptString(optional) "true" or "false", accept the task before initiating call. Defaults to "false". Needs to be a string. Eg: "true", not true
resultCallbackFunction(optional) A JavaScript Function that will be called upon the completion of the redirect. If an error occurs, the first argument passed to this function will be an Error. If the call is successful, the first argument will be null and the second argument will contain the non-updated Reservation object. However, you can still utilize actions on it. See below.

_13
reservation.redirect(
_13
"CAxxxx", //redirectCallSid
_13
"https://handler.twilio.com/twiml/EH621f0e21da7ce5441f6ec6aacce64069", //redirectUrl
_13
"true", //redirectAccept
_13
function(error, reservation) { //resultCallback
_13
if(error) {
_13
console.log(error.code);
_13
console.log(error.message);
_13
return;
_13
}
_13
console.log("reservation call was redirected");
_13
}
_13
);

Note: The URL used in the example above is created using Twiml Bins which returns the following Twiml that plays "Hello from Twiml".


_10
<?xml version="1.0" encoding="UTF-8"?>
_10
<Response>
_10
<Say>Hello from Twilio!</Say>
_10
</Response>


Rate this page: