Skip to contentSkip to navigationSkip to topbar
On this page

TaskRouter.js v1 Workspace: Managing resources in the browser


The SDK allows developers to interact with the entire TaskRouter REST API by a simple JS API.


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 Workspace 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 (JWT) 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 Workspace.

We provide five helper methods to provide access capabilities (Note: These are not currently available in the Node.js library):

CapabilityAuthorization
AllowFetchSubresourcesA workspace can fetch any subresource
AllowUpdatesA workspace can update its properties
AllowUpdatesSubresourcesA workspace can update itself and any subresource
AllowDeleteA workspace can delete itself
AllowDeleteSubresourcesA workspace can delete itself and any subresource

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

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

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:

var workspace = new Twilio.TaskRouter.Workspace(WORKSPACE_TOKEN);

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

1
workspace.on("ready", function(workspace) {
2
console.log(workspace.sid) // 'WSxxx'
3
console.log(workspace.friendlyName) // 'Workspace 1'
4
console.log(workspace.prioritizeQueueOrder) // 'FIFO'
5
console.log(workspace.defaultActivityName) // 'Offline'
6
});

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


TaskRouter.js Workspace exposes the following API:


Twilio.TaskRouter.Workspace

taskrouterworkspace page anchor

Twilio.TaskRouter.Workspace is the top-level class you'll use for managing a workspace.

new Twilio.TaskRouter.Workspace(workspaceToken)

new-taskrouterworkspace page anchor

Register a new Twilio.TaskRouter.Workspace with the capabilities provided in workspaceToken.

Parameters

parameters page anchor
NameTypeDescription
workspaceTokenStringA 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.
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.
var workspace = new Twilio.TaskRouter.Workspace(WORKSPACE_TOKEN);

Turning off debugging:

var workspace = new Twilio.TaskRouter.Workspace(WORKSPACE_TOKEN, false);

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

update page anchor

Updates a single or list of properties on a workspace.

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 Workspace object.
Single Attribute Example
single-attribute-example page anchor
1
workspace.update("EventCallbackUrl", "http://requestb.in/1kmw9im1", function(error, workspace) {
2
if(error) {
3
console.log(error.code);
4
console.log(error.message);
5
} else {
6
console.log(workspace.eventCallbackUrl); // "http://requestb.in/1kmw9im1"
7
}
8
});
Multiple Attribute Example
multiple-attribute-example page anchor
1
var props = {"EventCallbackUrl", "http://requestb.in/1kmw9im1", "TimeoutActivitySid":"WAxxx"};
2
workspace.update(props, function(error, workspace) {
3
if(error) {
4
console.log(error.code);
5
console.log(error.message);
6
} else {
7
console.log(workspace.eventCallbackUrl); // "http://requestb.in/1kmw9im1"
8
console.log(workspace.timeoutActivitySid); // "WAxxx"
9
}
10
});

delete([resultCallback])

delete page anchor

Deletes a workspace

NameTypeDescription
resultCallbackFunction(optional) A JavaScript Function that will be called with the result of the delete. If an error occurs, the first argument passed to this function will be an Error. If the delete is successful, the first argument will be null.
1
workspace.delete(function(error) {
2
if(error) {
3
console.log(error.code);
4
console.log(error.message);
5
} else {
6
console.log("workspace deleted");
7
}
8
});

updateToken(workspaceToken)

updatetoken page anchor

Updates the TaskRouter capability token for the Workspace.

NameTypeDescription
workspaceTokenStringA valid TaskRouter capability token.
1
var token = refreshJWT(); // your method to retrieve a new capability token
2
workspace.updateToken(token);

Retrieves the object to retrieve the list of activities, create a new activity, fetch, update or delete a specific activity.

NameTypeDescription
sidString(optional) SID to fetch
paramsJSON(optional) A JSON object of query parameters
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 activity list.
1
workspace.activities.fetch(
2
function(error, activityList) {
3
if(error) {
4
console.log(error.code);
5
console.log(error.message);
6
return;
7
}
8
console.log("Parsing response");
9
var data = activityList.data;
10
for(i=0; i<data.length; i++) {
11
console.log(data[i].friendlyName);
12
}
13
}
14
);
Fetching a specific Activity
fetching-a-specific-activity page anchor
1
workspace.activities.fetch("WAxxx",
2
function(error, activity) {
3
if(error) {
4
console.log(error.code);
5
console.log(error.message);
6
return;
7
}
8
console.log(activity.friendlyName);
9
}
10
);
NameTypeDescription
paramsJSONAn object containing multiple values
callbackFunctionA function that will be called when the created 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 create is successful, the first parameter will be null and the second parameter will contain the created instance.
1
var params = {"FriendlyName":"Activity1", "Available":"true"};
2
workspace.activities.create(
3
params,
4
function(error, activity) {
5
if(error) {
6
console.log(error.code);
7
console.log(error.message);
8
return;
9
}
10
console.log("FriendlyName: "+activity.friendlyName);
11
}
12
);

You can update an Activity resource in two manners:

  • Updating on an Instance Resource
  • Updating on the List Resource passing a specific SID

Instance Resource Parameters

instance-resource-parameters page anchor
NameTypeDescription
args...String or JSONA single API parameter and value or a JSON 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
workspace.activities.fetch(
2
function(error, activityList) {
3
if(error) {
4
console.log(error.code);
5
console.log(error.message);
6
return;
7
}
8
var data = activityList.data;
9
for(i=0; i<data.length; i++) {
10
var activity = data[i];
11
activity.update("WAxxx", "FriendlyName", "NewFriendlyName",
12
function(error, activity) {
13
if(error) {
14
console.log(error.code);
15
console.log(error.message);
16
return;
17
}
18
console.log("FriendlyName: "+activity.friendlyName);
19
}
20
);
21
}
22
}
23
);

List Resource Parameters

list-resource-parameters page anchor
NameTypeDescription
sidStringSID to update
args...String or JSONA single API parameter and value or a JSON 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
workspace.activities.update("WAxxx", "FriendlyName", "NewFriendlyName",
2
function(error, activity) {
3
if(error) {
4
console.log(error.code);
5
console.log(error.message);
6
return;
7
}
8
console.log("FriendlyName: "+activity.friendlyName);
9
}
10
);

You can delete an Activity resource in two manners:

  • Deleting on an Instance Resource
  • Deleting on the List Resource passing a specific SID

Instance Resource Parameters

instance-resource-parameters-2 page anchor
NameTypeDescription
resultCallbackFunction(optional) A JavaScript Function that will be called with the result of the delete. If an error occurs, the first argument passed to this function will be an Error. If the delete is successful, the first argument will be null.
1
workspace.activities.fetch(
2
function(error, activityList) {
3
if(error) {
4
console.log(error.code);
5
console.log(error.message);
6
return;
7
}
8
var data = activityList.data;
9
for(i=0; i<data.length; i++) {
10
var activity = data[i];
11
activity.delete(function(error) {
12
if(error) {
13
console.log(error.code);
14
console.log(error.message);
15
return;
16
}
17
console.log("Activity deleted");
18
});
19
}
20
}
21
);
NameTypeDescription
sidStringSID to delete
resultCallbackFunction(optional) A JavaScript Function that will be called with the result of the delete. If an error occurs, the first argument passed to this function will be an Error. If the delete is successful, the first argument will be null.
1
workspace.activities.delete("WAxxx"
2
function(error) {
3
if(error) {
4
console.log(error.code);
5
console.log(error.message);
6
return;
7
}
8
console.log("Activity deleted");
9
}
10
);

Retrieves the object to retrieve the list of workflows, create a new workflow, fetch, update or delete a specific workflow.

NameTypeDescription
sidString(optional) SID to fetch
paramsJSON(optional) A JSON object of query parameters
callbackFunctionA function that will be called when the workflow 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 a workflow list.
1
workspace.workflows.fetch(
2
function(error, workflowList) {
3
if(error) {
4
console.log(error.code);
5
console.log(error.message);
6
return;
7
}
8
console.log("Parsing response");
9
var data = workflowList.data;
10
for(i=0; i<data.length; i++) {
11
console.log(data[i].friendlyName);
12
}
13
}
14
);
Fetching a specific Workflow
fetching-a-specific-workflow page anchor
1
workspace.workflows.fetch("WWxxx",
2
function(error, workflow) {
3
if(error) {
4
console.log(error.code);
5
console.log(error.message);
6
return;
7
}
8
console.log(workflow.friendlyName);
9
}
10
);
NameTypeDescription
paramsJSONAn object containing multiple values
callbackFunctionA function that will be called when the created 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 create is successful, the first parameter will be null and the second parameter will contain the created instance.
1
var workflowConfig = {"task_routing":{"default_filter":{"task_queue_sid":"WQxxx"}}};
2
var params = {"FriendlyName":"Workflow1", "AssignmentCallbackUrl":"http://requestb.in/1kmw9im1", "Configuration":workflowConfig};
3
workspace.workflows.create(
4
params,
5
function(error, workflow) {
6
if(error) {
7
console.log(error.code);
8
console.log(error.message);
9
return;
10
}
11
console.log("FriendlyName: "+workflow.friendlyName);
12
}
13
);

You can update a Workflow resource in two manners:

  • Updating on an Instance Resource
  • Updating on the List Resource passing a specific SID

Instance Resource Parameters

instance-resource-parameters-3 page anchor
NameTypeDescription
args...String or JSONA single API parameter and value or a JSON 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
workspace.workflows.fetch(
2
function(error, workflowList) {
3
if(error) {
4
console.log(error.code);
5
console.log(error.message);
6
return;
7
}
8
var data = workflowList.data;
9
for(i=0; i<data.length; i++) {
10
var workflow = data[i];
11
workflow.update("WWxxx", "TaskReservationTimeout", "300",
12
function(error, workflow) {
13
if(error) {
14
console.log(error.code);
15
console.log(error.message);
16
return;
17
}
18
console.log("TaskReservationTimeout: "+workflow.taskReservationTimeout);
19
}
20
);
21
}
22
}
23
);
NameTypeDescription
sidStringSID to update
args...String or JSONA single API parameter and value or a JSON 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
workspace.workflows.update("WWxxx", "TaskReservationTimeout", "300",
2
function(error, workflow) {
3
if(error) {
4
console.log(error.code);
5
console.log(error.message);
6
return;
7
}
8
console.log("TaskReservationTimeout: "+workflow.taskReservationTimeout);
9
}
10
);

You can delete a Workflow resource in two manners:

  • Deleting on an Instance Resource
  • Deleting on the List Resource passing a specific SID

Instance Resource Parameters

instance-resource-parameters-4 page anchor
NameTypeDescription
resultCallbackFunction(optional) A JavaScript Function that will be called with the result of the delete. If an error occurs, the first argument passed to this function will be an Error. If the delete is successful, the first argument will be null.
1
workspace.workflows.fetch(
2
function(error, workflowList) {
3
if(error) {
4
console.log(error.code);
5
console.log(error.message);
6
return;
7
}
8
var data = workflowList.data;
9
for(i=0; i<data.length; i++) {
10
var workflow = data[i];
11
workflow.delete(function(error) {
12
if(error) {
13
console.log(error.code);
14
console.log(error.message);
15
return;
16
}
17
console.log("Workflow deleted");
18
}
19
);
20
}
21
}
22
);
NameTypeDescription
sidStringSID to delete
resultCallbackFunction(optional) A JavaScript Function that will be called with the result of the delete. If an error occurs, the first argument passed to this function will be an Error. If the delete is successful, the first argument will be null.
1
workspace.workflows.delete("WWxxx"
2
function(error) {
3
if(error) {
4
console.log(error.code);
5
console.log(error.message);
6
return;
7
}
8
console.log("Workflow deleted");
9
}
10
);

Retrieves the object to retrieve the statistics for a workflow.

NameTypeDescription
paramsJSON(optional) A JSON object of query parameters
callbackFunctionA function that will be called when the statistics object 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 a statistics object.
1
var queryParams = {"Minutes":"240"};
2
workflow.statistics.fetch(
3
queryParams,
4
function(error, statistics) {
5
if(error) {
6
console.log(error.code);
7
console.log(error.message);
8
return;
9
}
10
console.log("fetched workflow statistics: "+JSON.stringify(statistics));
11
}
12
);

Cumulative Stats:

1
var queryParams = {"Minutes":"240"};
2
workflow.cumulativeStats.fetch(
3
queryParams,
4
function(error, statistics) {
5
if(error) {
6
console.log(error.code);
7
console.log(error.message);
8
return;
9
}
10
console.log("fetched workflow statistics: "+JSON.stringify(statistics));
11
}
12
);

RealTime Stats:

1
workflow.realtimeStats.fetch(
2
function(error, statistics) {
3
if(error) {
4
console.log(error.code);
5
console.log(error.message);
6
return;
7
}
8
console.log("fetched workflow statistics: "+JSON.stringify(statistics));
9
}
10
);

Retrieves the object to retrieve the list of taskqueues, create a new taskqueue, fetch, update or delete a specific taskqueue.

NameTypeDescription
sidString(optional) SID to fetch
paramsJSON(optional) A JSON object of query parameters
callbackFunctionA function that will be called when the taskqueue 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 a taskqueue list.
1
workspace.taskqueues.fetch(
2
function(error, taskQueueList) {
3
if(error) {
4
console.log(error.code);
5
console.log(error.message);
6
return;
7
}
8
console.log("Parsing response");
9
var data = taskQueueList.data;
10
for(i=0; i<data.length; i++) {
11
console.log(data[i].friendlyName);
12
}
13
}
14
);
Fetching a specific TaskQueue
fetching-a-specific-taskqueue page anchor
1
workspace.taskqueues.fetch("WQxxx",
2
function(error, taskQueue) {
3
if(error) {
4
console.log(error.code);
5
console.log(error.message);
6
return;
7
}
8
console.log(taskQueue.friendlyName);
9
}
10
);
NameTypeDescription
paramsJSONAn object containing multiple values
callbackFunctionA function that will be called when the created 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 create is successful, the first parameter will be null and the second parameter will contain the created instance.
1
var params = {"FriendlyName":"TaskQueue1", "ReservationActivitySid":"WAxxx", "AssignmentActivitySid":"WAxxx", "TargetWorkers":"1==1"};
2
workspace.taskqueues.create(
3
params,
4
function(error, taskQueue) {
5
if(error) {
6
console.log(error.code);
7
console.log(error.message);
8
return;
9
}
10
console.log("FriendlyName: "+taskQueue.friendlyName);
11
}
12
);

You can update a TaskQueue resource in two manners:

  • Updating on an Instance Resource
  • Updating on the List Resource passing a specific SID

Instance Resource Parameters

instance-resource-parameters-5 page anchor
NameTypeDescription
args...String or JSONA single API parameter and value or a JSON 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
workspace.taskqueues.fetch(
2
function(error, taskQueueList) {
3
if(error) {
4
console.log(error.code);
5
console.log(error.message);
6
return;
7
}
8
var data = taskQueueList.data;
9
for(i=0; i<data.length; i++) {
10
var taskqueue = data[i];
11
taskqueue.update("WWxxx", "MaxReservedWorkers", "20",
12
function(error, taskqueue) {
13
if(error) {
14
console.log(error.code);
15
console.log(error.message);
16
return;
17
}
18
console.log("MaxReservedWorkers: "+taskqueue.maxReservedWorkers);
19
}
20
);
21
}
22
}
23
);
NameTypeDescription
sidStringSID to update
args...String or JSONA single API parameter and value or a JSON 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
workspace.taskqueues.update("WQxxx", "MaxReservedWorkers", "20",
2
function(error, taskqueue) {
3
if(error) {
4
console.log(error.code);
5
console.log(error.message);
6
return;
7
}
8
console.log("MaxReservedWorkers: "+taskqueue.maxReservedWorkers);
9
}
10
);

You can delete a TaskQueue resource in two manners:

  • Deleting on an Instance Resource
  • Deleting on the List Resource passing a specific SID

Instance Resource Parameters

instance-resource-parameters-6 page anchor
NameTypeDescription
resultCallbackFunction(optional) A JavaScript Function that will be called with the result of the delete. If an error occurs, the first argument passed to this function will be an Error. If the delete is successful, the first argument will be null.
1
workspace.taskqueues.fetch(
2
function(error, taskQueueList) {
3
if(error) {
4
console.log(error.code);
5
console.log(error.message);
6
return;
7
}
8
var data = taskQueueList.data;
9
for(i=0; i<data.length; i++) {
10
var taskqueue = data[i];
11
taskqueue.delete(function(error) {
12
if(error) {
13
console.log(error.code);
14
console.log(error.message);
15
return;
16
}
17
console.log("TaskQueue deleted");
18
}
19
);
20
}
21
}
22
);
NameTypeDescription
sidStringSID to delete
resultCallbackFunction(optional) A JavaScript Function that will be called with the result of the delete. If an error occurs, the first argument passed to this function will be an Error. If the delete is successful, the first argument will be null.
1
workspace.taskqueues.delete("WQxxx"
2
function(error) {
3
if(error) {
4
console.log(error.code);
5
console.log(error.message);
6
return;
7
}
8
console.log("TaskQueue deleted");
9
}
10
);

Retrieves the object to retrieve the statistics for a taskqueue.

NameTypeDescription
paramsJSON(optional) A JSON object of query parameters
callbackFunctionA function that will be called when the statistics object 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 a statistics object.

List of TaskQueues:

1
var queryParams = {"Minutes":"240"};
2
workspace.taskqueues.statistics.fetch(
3
queryParams,
4
function(error, statistics) {
5
if(error) {
6
console.log(error.code);
7
console.log(error.message);
8
return;
9
}
10
console.log("fetched taskqueues statistics: "+JSON.stringify(statistics));
11
}
12
);

Single TaskQueue:

1
var queryParams = {"Minutes":"240"};
2
taskqueue.statistics.fetch(
3
queryParams,
4
function(error, statistics) {
5
if(error) {
6
console.log(error.code);
7
console.log(error.message);
8
return;
9
}
10
console.log("fetched taskqueue statistics: "+JSON.stringify(statistics));
11
}
12
);

Note: Replace statistics with cumulativestats or realtimestats if you only care about cumulative or real time stats for faster response times and a smaller payload.

Cumulative Stats:

1
taskqueue.cumulativeStats.fetch(
2
function(error, statistics) {
3
if(error) {
4
console.log(error.code);
5
console.log(error.message);
6
return;
7
}
8
console.log("fetched taskqueue statistics: "+JSON.stringify(statistics));
9
console.log("avg task acceptance time: "+statistics.avgTaskAcceptanceTime;
10
}
11
);

RealTime Stats:

1
var queryParams = {"Minutes":"240"};
2
taskqueue.realtimeStats.fetch(
3
queryParams,
4
function(error, statistics) {
5
if(error) {
6
console.log(error.code);
7
console.log(error.message);
8
return;
9
}
10
console.log("fetched taskqueue statistics: "+JSON.stringify(statistics));
11
console.log("total available workers: "+statistics.totalAvailableWorkers;
12
}
13
);

Retrieves the object to retrieve the list of workers, create a new worker, fetch, update or delete a specific worker.

NameTypeDescription
sidString(optional) SID to fetch
paramsJSON(optional) A JSON object of query parameters
callbackFunctionA function that will be called when the worker 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 worker list.
1
workspace.workers.fetch(
2
function(error, workerList) {
3
if(error) {
4
console.log(error.code);
5
console.log(error.message);
6
return;
7
}
8
console.log("Parsing response");
9
var data = workerList.data;
10
for(i=0; i<data.length; i++) {
11
console.log(data[i].friendlyName);
12
}
13
}
14
);
Fetching a specific Worker
fetching-a-specific-worker page anchor
1
workspace.workers.fetch("WKxxx",
2
function(error, worker) {
3
if(error) {
4
console.log(error.code);
5
console.log(error.message);
6
return;
7
}
8
console.log(worker.friendlyName);
9
}
10
);
NameTypeDescription
paramsJSONAn object containing multiple values
callbackFunctionA function that will be called when the created 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 create is successful, the first parameter will be null and the second parameter will contain the created instance.
1
var params = {"FriendlyName":"Worker1"};
2
workspace.workers.create(
3
params,
4
function(error, worker) {
5
if(error) {
6
console.log(error.code);
7
console.log(error.message);
8
return;
9
}
10
console.log("FriendlyName: "+worker.friendlyName);
11
}
12
);

You can update a Worker resource in two manners:

  • Updating on an Instance Resource
  • Updating on the List Resource passing a specific SID

Instance Resource Parameters

instance-resource-parameters-7 page anchor
NameTypeDescription
args...String or JSONA single API parameter and value or a JSON 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
workspace.workers.fetch(
2
function(error, workerList) {
3
if(error) {
4
console.log(error.code);
5
console.log(error.message);
6
return;
7
}
8
var data = workerList.data;
9
for(i=0; i<data.length; i++) {
10
var worker = data[i];
11
worker.update("WKxxx", "ActivitySid", "WAxxx",
12
function(error, worker) {
13
if(error) {
14
console.log(error.code);
15
console.log(error.message);
16
return;
17
}
18
console.log("FriendlyName: "+worker.friendlyName);
19
}
20
);
21
}
22
}
23
);
NameTypeDescription
sidStringSID to update
args...String or JSONA single API parameter and value or a JSON 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
workspace.workers.update("WKxxx", "ActivitySid", "WAxxx",
2
function(error, worker) {
3
if(error) {
4
console.log(error.code);
5
console.log(error.message);
6
return;
7
}
8
console.log("FriendlyName: "+worker.friendlyName);
9
}
10
);

You can delete a Worker resource in two manners:

  • Deleting on an Instance Resource
  • Deleting on the List Resource passing a specific SID

Instance Resource Parameters

instance-resource-parameters-8 page anchor
NameTypeDescription
resultCallbackFunction(optional) A JavaScript Function that will be called with the result of the delete. If an error occurs, the first argument passed to this function will be an Error. If the delete is successful, the first argument will be null.
1
workspace.workers.fetch(
2
function(error, workerList) {
3
if(error) {
4
console.log(error.code);
5
console.log(error.message);
6
return;
7
}
8
var data = workerList.data;
9
for(i=0; i<data.length; i++) {
10
var worker = data[i];
11
worker.delete(function(error) {
12
if(error) {
13
console.log(error.code);
14
console.log(error.message);
15
return;
16
}
17
console.log("Worker deleted");
18
}
19
);
20
}
21
}
22
);
NameTypeDescription
sidStringSID to delete
resultCallbackFunction(optional) A JavaScript Function that will be called with the result of the delete. If an error occurs, the first argument passed to this function will be an Error. If the delete is successful, the first argument will be null.
1
workspace.workers.delete("WKxxx"
2
function(error) {
3
if(error) {
4
console.log(error.code);
5
console.log(error.message);
6
return;
7
}
8
console.log("Worker deleted");
9
}
10
);

Retrieves the object to retrieve the statistics for a worker.

NameTypeDescription
paramsJSON(optional) A JSON object of query parameters
callbackFunctionA function that will be called when the statistics object 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 a statistics object.

List of Workers:

1
var queryParams = {"Minutes":"240"};
2
workspace.workers.statistics.fetch(
3
queryParams,
4
function(error, statistics) {
5
if(error) {
6
console.log(error.code);
7
console.log(error.message);
8
return;
9
}
10
console.log("fetched workers statistics: "+JSON.stringify(statistics));
11
}
12
);

List of Workers Cumulative Stats:

1
var queryParams = {"Minutes":"240"};
2
workspace.workers.cumulativeStats.fetch(
3
queryParams,
4
function(error, statistics) {
5
if(error) {
6
console.log(error.code);
7
console.log(error.message);
8
return;
9
}
10
console.log("fetched workers statistics: "+JSON.stringify(statistics));
11
}
12
);

List of Workers RealTime Stats:

1
workspace.workers.realtimeStats.fetch(
2
function(error, statistics) {
3
if(error) {
4
console.log(error.code);
5
console.log(error.message);
6
return;
7
}
8
console.log("fetched workers statistics: "+JSON.stringify(statistics));
9
}
10
);

Single Worker:

1
var queryParams = {"Minutes":"240"};
2
worker.statistics.fetch(
3
queryParams,
4
function(error, statistics) {
5
if(error) {
6
console.log(error.code);
7
console.log(error.message);
8
return;
9
}
10
console.log("fetched worker statistics: "+JSON.stringify(statistics));
11
}
12
);

Retrieves the object to retrieve the list of tasks, create a new task, fetch, update or delete a specific task.

NameTypeDescription
sidString(optional) SID to fetch
paramsJSON(optional) A JSON object of query parameters
callbackFunctionA function that will be called when the task 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 task list.
1
workspace.tasks.fetch(
2
function(error, taskList) {
3
if(error) {
4
console.log(error.code);
5
console.log(error.message);
6
return;
7
}
8
console.log("Parsing response");
9
var data = taskList.data;
10
for(i=0; i<data.length; i++) {
11
console.log(JSON.stringify(data[i].attributes));
12
}
13
}
14
);
Fetching a specific Task
fetching-a-specific-task page anchor
1
workspace.tasks.fetch("WTxxx",
2
function(error, task) {
3
if(error) {
4
console.log(error.code);
5
console.log(error.message);
6
return;
7
}
8
console.log(JSON.stringify(task.attributes));
9
}
10
);
NameTypeDescription
paramsJSONAn object containing multiple values
callbackFunctionA function that will be called when the created 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 create is successful, the first parameter will be null and the second parameter will contain the created instance.
1
var attributes = "{\"Ticket\":\"Gold\"}";
2
var params = {"WorkflowSid":"WWxxx", "Attributes":attributes};
3
workspace.tasks.create(
4
params,
5
function(error, task) {
6
if(error) {
7
console.log(error.code);
8
console.log(error.message);
9
return;
10
}
11
console.log("TaskSid: "+task.sid);
12
}
13
);

You can update a Task resource in two manners:

  • Updating on an Instance Resource
  • Updating on the List Resource passing a specific SID

Instance Resource Parameters

instance-resource-parameters-9 page anchor
NameTypeDescription
args...String or JSONA single API parameter and value or a JSON 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
workspace.tasks.fetch(
2
function(error, taskList) {
3
if(error) {
4
console.log(error.code);
5
console.log(error.message);
6
return;
7
}
8
var data = taskList.data;
9
var cancelAttrs = {"AssignmentStatus":"canceled", "Reason":"waiting"}
10
for(i=0; i<data.length; i++) {
11
var task = data[i];
12
task.update("WTxxx", cancelAttrs,
13
function(error, task) {
14
if(error) {
15
console.log(error.code);
16
console.log(error.message);
17
return;
18
}
19
console.log("Attributes: "+JSON.stringify(task.attributes));
20
}
21
);
22
}
23
}
24
);
NameTypeDescription
sidStringSID to update
args...String or JSONA single API parameter and value or a JSON 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
var cancelAttrs = {"AssignmentStatus":"canceled", "Reason":"waiting"}
2
workspace.tasks.update("WTxxx", cancelAttrs,
3
function(error, task) {
4
if(error) {
5
console.log(error.code);
6
console.log(error.message);
7
return;
8
}
9
console.log("Attributes: "+JSON.stringify(task.attributes));
10
}
11
);

You can delete a Task resource in two manners:

  • Deleting on an Instance Resource
  • Deleting on the List Resource passing a specific SID
NameTypeDescription
resultCallbackFunction(optional) A JavaScript Function that will be called with the result of the delete. If an error occurs, the first argument passed to this function will be an Error. If the delete is successful, the first argument will be null.
1
workspace.tasks.fetch(
2
function(error, taskList) {
3
if(error) {
4
console.log(error.code);
5
console.log(error.message);
6
return;
7
}
8
var data = taskList.data;
9
for(i=0; i<data.length; i++) {
10
var task = data[i];
11
task.delete(function(error) {
12
if(error) {
13
console.log(error.code);
14
console.log(error.message);
15
return;
16
}
17
console.log("Task deleted");
18
}
19
);
20
}
21
}
22
);
NameTypeDescription
sidStringSID to delete
resultCallbackFunction(optional) A JavaScript Function that will be called with the result of the delete. If an error occurs, the first argument passed to this function will be an Error. If the delete is successful, the first argument will be null.
1
workspace.tasks.delete("WTxxx"
2
function(error) {
3
if(error) {
4
console.log(error.code);
5
console.log(error.message);
6
return;
7
}
8
console.log("task deleted");
9
}
10
);

Retrieves the object to retrieve the statistics for a workspace.

NameTypeDescription
paramsJSON(optional) A JSON object of query parameters
callbackFunctionA function that will be called when the statistics object 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 a statistics object.
1
var queryParams = {"Minutes":"240"};
2
workspace.statistics.fetch(
3
queryParams,
4
function(error, statistics) {
5
if(error) {
6
console.log(error.code);
7
console.log(error.message);
8
return;
9
}
10
console.log("fetched workspace statistics: "+JSON.stringify(statistics));
11
}
12
);

Cumulative Stats:

1
var queryParams = {"Minutes":"240"};
2
workspace.cumulativeStats.fetch(
3
queryParams,
4
function(error, statistics) {
5
if(error) {
6
console.log(error.code);
7
console.log(error.message);
8
return;
9
}
10
console.log("fetched workspace statistics: "+JSON.stringify(statistics));
11
}
12
);

RealTime Stats:

1
var queryParams = {};
2
workspace.realtimeStats.fetch(
3
queryParams,
4
function(error, statistics) {
5
if(error) {
6
console.log(error.code);
7
console.log(error.message);
8
return;
9
}
10
console.log("fetched workspace statistics: "+JSON.stringify(statistics));
11
}
12
);

on(event, callback)

workspace-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
workspace.on("ready", function(workspace) {
2
console.log(workspace.friendlyName) // MyWorkspace
3
});

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

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

NameTypeDescription
workspaceWorkspaceThe Workspace object for the Workspace you've created.
1
workspace.on("ready", function(workspace) {
2
console.log(workspace.friendlyName) // MyWorkspace
3
});

The Workspace has established a connection to TaskRouter.

1
workspace.on("connected", function() {
2
console.log("Websocket has connected");
3
});

The Workspace has disconnected from TaskRouter.

1
workspace.on("disconnected", function() {
2
console.log("Websocket has disconnected");
3
});

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

1
workspace.on("token.expired", function() {
2
console.log("updating token");
3
var token = refreshJWT(); // your method to retrieve a new capability token
4
workspace.updateToken(token);
5
});

Need some help?

Terms of service

Copyright © 2024 Twilio Inc.