Skip to contentSkip to navigationSkip to topbar
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
  • 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:

<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 tokenLink to code sample: Creating a TaskRouter Worker capability token
1
// Download the Node helper library from twilio.com/docs/node/install
2
// These consts are your accountSid and authToken from https://www.twilio.com/console
3
const taskrouter = require('twilio').jwt.taskrouter;
4
const util = taskrouter.util;
5
6
const TaskRouterCapability = taskrouter.TaskRouterCapability;
7
const Policy = TaskRouterCapability.Policy;
8
9
// To set up environmental variables, see http://twil.io/secure
10
const accountSid = process.env.TWILIO_ACCOUNT_SID;
11
const authToken = process.env.TWILIO_AUTH_TOKEN;
12
const workspaceSid = 'WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
13
const workerSid = 'WKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
14
15
const TASKROUTER_BASE_URL = 'https://taskrouter.twilio.com';
16
const version = 'v1';
17
18
const capability = new TaskRouterCapability({
19
accountSid: accountSid,
20
authToken: authToken,
21
workspaceSid: workspaceSid,
22
channelId: workerSid});
23
24
// Helper function to create Policy
25
function buildWorkspacePolicy(options) {
26
options = options || {};
27
var resources = options.resources || [];
28
var urlComponents = [TASKROUTER_BASE_URL, version, 'Workspaces', workspaceSid]
29
30
return new Policy({
31
url: urlComponents.concat(resources).join('/'),
32
method: options.method || 'GET',
33
allow: true
34
});
35
}
36
37
// Event Bridge Policies
38
const eventBridgePolicies = util.defaultEventBridgePolicies(accountSid, workerSid);
39
40
// Worker Policies
41
const workerPolicies = util.defaultWorkerPolicies(version, workspaceSid, workerSid);
42
43
const workspacePolicies = [
44
// Workspace fetch Policy
45
buildWorkspacePolicy(),
46
// Workspace subresources fetch Policy
47
buildWorkspacePolicy({ resources: ['**'] }),
48
// Workspace Activities Update Policy
49
buildWorkspacePolicy({ resources: ['Activities'], method: 'POST' }),
50
// Workspace Activities Worker Reserations Policy
51
buildWorkspacePolicy({ resources: ['Workers', workerSid, 'Reservations', '**'], method: 'POST' }),
52
];
53
54
eventBridgePolicies.concat(workerPolicies).concat(workspacePolicies).forEach(function (policy) {
55
capability.addPolicy(policy);
56
});
57
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 initialize the JavaScript library as follows:

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

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

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

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.

Parameters

parameters page anchor
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.
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);

Turning off debugging:

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

Adding Connecting and Disconnecting Activities, and closing Existing Sessions

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
1
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);
2
3
worker.update("ActivitySid", "WAxxx", function(error, worker) {
4
if(error) {
5
console.log(error.code);
6
console.log(error.message);
7
} else {
8
console.log(worker.activityName); // "Offline"
9
}
10
});
Multiple Attribute Example
multiple-attribute-example page anchor
1
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);
2
3
const props = {"ActivitySid":"WAxxx", "FriendlyName":"UpdatedWorker"};
4
5
worker.update(props, function(error, worker) {
6
if(error) {
7
console.log(error.code);
8
console.log(error.message);
9
} else {
10
console.log(worker.activityName); // "Offline"
11
}
12
});

updateToken(workerToken)

updatetoken page anchor

Updates the TaskRouter capability token for the Worker.

NameTypeDescription
workerTokenStringA valid TaskRouter capability token.
1
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);
2
3
const token = refreshJWT(); // your method to retrieve a new capability token
4
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
1
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);
2
3
worker.activities.fetch(
4
function(error, activityList) {
5
if(error) {
6
console.log(error.code);
7
console.log(error.message);
8
return;
9
}
10
const data = activityList.data;
11
for(i=0; i<data.length; i++) {
12
console.log(data[i].friendlyName);
13
}
14
}
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
1
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);
2
3
worker.fetchReservations(
4
function(error, reservations) {
5
if(error) {
6
console.log(error.code);
7
console.log(error.message);
8
return;
9
}
10
const data = reservations.data;
11
for(i=0; i<data.length; i++) {
12
console.log(data[i].sid);
13
}
14
}
15
);

The following will fetch just pending reservations:

1
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);
2
3
const queryParams = {"ReservationStatus":"pending"};
4
5
worker.fetchReservations(
6
function(error, reservations) {
7
if(error) {
8
console.log(error.code);
9
console.log(error.message);
10
return;
11
}
12
const data = reservations.data;
13
for(i=0; i<data.length; i++) {
14
console.log(data[i].sid);
15
}
16
},
17
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
1
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);
2
3
worker.fetchChannels(
4
function(error, channels) {
5
if(error) {
6
console.log(error.code);
7
console.log(error.message);
8
return;
9
}
10
const data = channels.data;
11
for(i=0; i<data.length; i++) {
12
console.log(data[i].taskChannelUniqueName + " with capacity: " + data[i].configuredCapacity);
13
}
14
}
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.
1
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);
2
3
const params = {"Priority":"15"};
4
worker.updateTask(taskSid, params,
5
function(error, updatedTask) {
6
if(error) {
7
console.log(error.code);
8
console.log(error.message);
9
return;
10
}
11
console.log("Updated Task Priority: "+updatedTask.priority);
12
}
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
1
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);
2
3
worker.completeTask(taskSid,
4
function(error, completedTask) {
5
if(error) {
6
console.log(error.code);
7
console.log(error.message);
8
return;
9
}
10
console.log("Completed Task: "+completedTask.assignmentStatus);
11
}
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
reservation.task.complete();

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

1
reservation.task.complete(
2
function(error, completedTask) {
3
if(error) {
4
console.log(error.code);
5
console.log(error.message);
6
return;
7
}
8
console.log("Completed Task: "+completedTask.assignmentStatus);
9
}
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.
1
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);
2
3
worker.on("activity.update", function(worker) {
4
console.log(worker.activityName) // 'Reserved'
5
console.log(worker.activitySid) // 'WAxxx'
6
console.log(worker.available) // false
7
});

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.
1
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);
2
3
worker.on("ready", function(worker) {
4
console.log(worker.available) // true
5
});

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
1
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);
2
3
worker.on("activity.update", function(worker) {
4
console.log(worker.sid) // 'WKxxx'
5
console.log(worker.friendlyName) // 'Worker 1'
6
console.log(worker.activityName) // 'Reserved'
7
console.log(worker.available) // false
8
});

The Worker's attributes have been updated.

NameTypeDescription
workerWorkerThe updated Worker object
1
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);
2
3
worker.on("attributes.update", function(worker) {
4
console.log(worker.sid) // 'WKxxx'
5
console.log(worker.friendlyName) // 'Worker 1'
6
console.log(worker.activityName) // 'Reserved'
7
console.log(worker.available) // false
8
});

The Worker's Capacity have been updated.

NameTypeDescription
channelWorkerChannelThe updated WorkerChannel object
1
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);
2
3
worker.on("capacity.update", function(channel) {
4
console.log(channel.sid) // 'WCxxx'
5
console.log(channel.taskChannelUniqueName) // 'ipm'
6
console.log(channel.available) // true
7
console.log(channel.configuredCapacity) // '3'
8
console.log(channel.availableCapacityPercentage) // 66.7
9
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.

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

Raised when the Worker has accepted a Reservation.

NameTypeDescription
reservationReservationThe Reservation object that has been accepted for this worker.
1
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);
2
3
worker.on("reservation.accepted", function(reservation) {
4
console.log(reservation.task.attributes) // {foo: 'bar', baz: 'bang' }
5
console.log(reservation.task.priority) // 1
6
console.log(reservation.task.age) // 300
7
console.log(reservation.task.sid) // WTxxx
8
console.log(reservation.sid) // WRxxx
9
});

Raised when the Worker has rejected a Reservation

NameTypeDescription
reservationReservationThe Reservation object that has been rejected for this worker.
1
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);
2
3
worker.on("reservation.rejected", function(reservation) {
4
console.log(reservation.task.attributes) // {foo: 'bar', baz: 'bang' }
5
console.log(reservation.task.priority) // 1
6
console.log(reservation.task.age) // 300
7
console.log(reservation.task.sid) // WTxxx
8
console.log(reservation.sid) // WRxxx
9
});

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

NameTypeDescription
reservationReservationThe Reservation object that has been timed-out for this worker.
1
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);
2
3
worker.on("reservation.timeout", function(reservation) {
4
console.log(reservation.task.attributes) // {foo: 'bar', baz: 'bang' }
5
console.log(reservation.task.priority) // 1
6
console.log(reservation.task.age) // 300
7
console.log(reservation.task.sid) // WTxxx
8
console.log(reservation.sid) // WRxxx
9
});

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
1
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);
2
3
worker.on("reservation.canceled", function(reservation) {
4
console.log(reservation.task.attributes) // {foo: 'bar', baz: 'bang' }
5
console.log(reservation.task.priority) // 1
6
console.log(reservation.task.age) // 300
7
console.log(reservation.task.sid) // WTxxx
8
console.log(reservation.sid) // WRxxx
9
});

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
1
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);
2
3
worker.on("reservation.rescinded", function(reservation) {
4
console.log(reservation.task.attributes) // {foo: 'bar', baz: 'bang' }
5
console.log(reservation.task.priority) // 1
6
console.log(reservation.task.age) // 300
7
console.log(reservation.task.sid) // WTxxx
8
console.log(reservation.sid) // WRxxx
9
});

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

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

Raised when the Websocket connects.

1
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);
2
3
worker.on("connected", function() {
4
console.log("Websocket has connected");
5
});

Raised when the Websocket disconnects.

1
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);
2
3
worker.on("disconnected", function() {
4
console.log("Websocket has disconnected");
5
});

Raised when the Websocket has an error.

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

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.
1
reservation.accept(
2
function(error, reservation) {
3
if(error) {
4
console.log(error.code);
5
console.log(error.message);
6
return;
7
}
8
console.log("reservation accepted");
9
for (const property in reservation) {
10
console.log(property+" : "+reservation[property]);
11
}
12
}
13
);

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

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.
1
reservation.reject(
2
function(error, reservation) {
3
if(error) {
4
console.log(error.code);
5
console.log(error.message);
6
return;
7
}
8
console.log("reservation rejected");
9
for (const property in reservation) {
10
console.log(property+" : "+reservation[property]);
11
}
12
}
13
);

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

reservation.reject();

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

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:

reservation.conference();

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

1
reservation.conference(
2
"18004746453",
3
"WAxxx",
4
"30",
5
"client:joey",
6
function(error, reservation) {
7
if(error) {
8
console.log(error.code);
9
console.log(error.message);
10
return;
11
}
12
console.log("conference initiated");
13
}
14
);

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

1
const options = {
2
"ConferenceStatusCallback": "https://requestb.in/wzfljiwz",
3
"ConferenceStatusCallbackEvent": "start,end",
4
"ConferenceRecord": "true",
5
"ConferenceRecordingStatusCallback": "https://requestb.in/wzfljiwz",
6
"EndConferenceOnExit": "true"
7
}
8
9
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:

1
const options = {
2
"From": "18004746453",
3
"PostWorkActivitySid": "WAxxx",
4
"Timeout": "30",
5
"To": "client:joey",
6
"Record":"true",
7
"ConferenceStatusCallback": "https://requestb.in/wzfljiwz",
8
"ConferenceStatusCallbackEvent": "start,end,join,leave"
9
}
10
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:

reservation.dequeue();

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

1
reservation.dequeue(
2
"18004746453",
3
"WAxxx",
4
"record-from-answer",
5
"30",
6
"http://requestb.in/13285vq1",
7
"client:joey",
8
function(error, reservation) {
9
if(error) {
10
console.log(error.code);
11
console.log(error.message);
12
return;
13
}
14
console.log("reservation dequeued");
15
}
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.
1
reservation.call(
2
"18004746453",
3
"http://twimlbin.com/451369ae",
4
"http://requestb.in/13285vq1",
5
"true",
6
"record-from-answer",
7
"client:joey"
8
function(error, reservation) {
9
if(error) {
10
console.log(error.code);
11
console.log(error.message);
12
return;
13
}
14
console.log("reservation called the worker");
15
}
16
);

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

1
reservation.call(
2
"18004746453",
3
"http://twimlbin.com/451369ae",
4
"http://requestb.in/13285vq1",
5
"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:

1
reservation.call(
2
"18004746453",
3
"http://twimlbin.com/451369ae",
4
null,
5
null,
6
null,
7
null,
8
function(error, reservation) {
9
if(error) {
10
console.log(error.code);
11
console.log(error.message);
12
return;
13
}
14
reservation.accept();
15
}
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:

1
reservation.call(
2
"18004746453",
3
"http://twimlbin.com/451369ae",
4
null,
5
"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.
1
reservation.redirect(
2
"CAxxxx", //redirectCallSid
3
"https://handler.twilio.com/twiml/EH621f0e21da7ce5441f6ec6aacce64069", //redirectUrl
4
"true", //redirectAccept
5
function(error, reservation) { //resultCallback
6
if(error) {
7
console.log(error.code);
8
console.log(error.message);
9
return;
10
}
11
console.log("reservation call was redirected");
12
}
13
);

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

1
<?xml version="1.0" encoding="UTF-8"?>
2
<Response>
3
<Say>Hello from Twilio!</Say>
4
</Response>

Need some help?

Terms of service

Copyright © 2024 Twilio Inc.