The following documentation is for the JS SDK V1. If you're working with the Twilio Flex SDK, head over to the TaskRouter.js documentation on Github.
The SDK allows developers to interact with the entire TaskRouter REST API by a simple JS API.
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>
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 TaskQueue.
We provide three relevant helper methods to provide access capabilities:
Capability | Authorization |
---|---|
AllowFetchSubresources | A TaskQueue can fetch any subresource (statistics) |
AllowUpdates | A TaskQueue can update its properties |
AllowDelete | A TaskQueue can delete itself |
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, the WorkspaceSid the TaskQueue belongs to and the TaskQueueSid you would like to register. For example, using our PHP helper library you can create a token and add capabilities as follows:
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:
_10var taskQueue = new Twilio.TaskRouter.TaskQueue(TASKQUEUE_TOKEN);
The library will raise a 'ready' event once it has connected to TaskRouter:
_10taskQueue.on("ready", function(taskQueue) {_10 console.log(taskQueue.sid) // 'WQxxx'_10 console.log(taskQueue.friendlyName) // 'Simple FIFO Queue'_10 console.log(taskQueue.targetWorkers) // '1==1'_10 console.log(taskQueue.maxReservedWorkers) // 20_10});
See more about the methods and events exposed on this object below.
TaskRouter.js TaskQueue exposes the following API:
Twilio.TaskRouter.TaskQueue is the top-level class you'll use for managing a TaskQueue.
Register a new Twilio.TaskRouter.TaskQueue with the capabilities provided in taskQueueToken
.
Name | Type | Description |
---|---|---|
taskQueueToken | String | A Twilio TaskRouter capability token. See Creating a TaskRouter capability token for more information. |
debug | Boolean | (optional) Whether or not the JS SDK will print event messages to the console. Defaults to true. |
region | String | (optional) A Twilio region for websocket connections (ex. ie1-ix ). |
maxRetries | Integer | (optional) The maximum of retries to attempt if a websocket request fails. Defaults to 0. |
_10var taskQueue = new Twilio.TaskRouter.TaskQueue(TASKQUEUE_TOKEN);
Turning off debugging:
_10var taskQueue = new Twilio.TaskRouter.TaskQueue(TASKQUEUE_TOKEN, false);
Updates a single or list of properties on a TaskQueue.
Name | Type | Description |
---|---|---|
args... | String or JSON | A single API parameter and value or a JSON object containing multiple values |
resultCallback | Function | (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 TaskQueue. |
_10taskQueue.update("MaxReservedWorkers", "20", function(error, taskQueue) {_10 if(error) {_10 console.log(error.code);_10 console.log(error.message);_10 } else {_10 console.log(taskQueue.maxReservedWorkers); // 20_10 }_10});
_11var targetWorkers = "languages HAS \"english\"";_11var props = {"MaxReservedWorkers", "20", "TargetWorkers":targetWorkers};_11taskQueue.update(props, function(error, workspace) {_11 if(error) {_11 console.log(error.code);_11 console.log(error.message);_11 } else {_11 console.log(taskQueue.maxReservedWorkers); // "20"_11 console.log(taskQueue.targetWorkers); // "languages HAS "english""_11 }_11});
Deletes a TaskQueue
Name | Type | Description |
---|---|---|
resultCallback | Function | (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. |
_10taskQueue.delete(function(error) {_10 if(error) {_10 console.log(error.code);_10 console.log(error.message);_10 } else {_10 console.log("taskQueue deleted");_10 }_10});
Updates the TaskRouter capability token for the Workspace.
Name | Type | Description |
---|---|---|
taskQueueToken | String | A valid TaskRouter capability token. |
_10var token = refreshJWT(); // your method to retrieve a new capability token_10taskQueue.updateToken(token);
Retrieves the object to retrieve the statistics for a TaskQueue.
Name | Type | Description |
---|---|---|
params | JSON | (optional) A JSON object of query parameters |
callback | Function | A 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. |
_13var queryParams = {"Minutes":"240"}; // 4 hours_13taskQueue.statistics.fetch(_13 queryParams,_13 function(error, statistics) {_13 if(error) {_13 console.log(error.code);_13 console.log(error.message);_13 return;_13 }_13 console.log("fetched taskQueue statistics: "+JSON.stringify(statistics));_13 console.log("avg task acceptance time: "+statistics.cumulative.avgTaskAcceptanceTime;_13 }_13);
If you only care about the cumulative stats for a TaskQueue for a given time period, you can utilize this instead of the above for a smaller payload and faster response time.
Name | Type | Description |
---|---|---|
params | JSON | (optional) A JSON object of query parameters |
callback | Function | A 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. |
_13var queryParams = {"Minutes":"240"}; // 4 hours_13taskQueue.cumulativeStats.fetch(_13 queryParams,_13 function(error, statistics) {_13 if(error) {_13 console.log(error.code);_13 console.log(error.message);_13 return;_13 }_13 console.log("fetched taskQueue statistics: "+JSON.stringify(statistics));_13 console.log("avg task acceptance time: "+statistics.avgTaskAcceptanceTime;_13 }_13);
If you only care about the realtime stats for a TaskQueue for a given time period, you can utilize this instead of the above for a smaller payload and faster response time.
Name | Type | Description |
---|---|---|
params | JSON | (optional) A JSON object of query parameters |
callback | Function | A 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. |
_12taskQueue.realtimeStats.fetch(_12 function(error, statistics) {_12 if(error) {_12 console.log(error.code);_12 console.log(error.message);_12 return;_12 }_12 console.log("fetched taskQueue statistics: "+JSON.stringify(statistics));_12 console.log("total available workers: "+statistics.totalAvailableWorkers;_12 console.log("total eligible workers: "+statistics.totalEligibleWorkers;_12 }_12);
Attaches a listener to the specified event. See Events for the complete list of supported events.
Name | Type | Description |
---|---|---|
event | String | An event name. See Events for the complete list of supported events. |
callback | Function | A function that will be called when the specified Event is raised. |
_10taskQueue.on("ready", function(taskQueue) {_10 console.log(taskQueue.friendlyName) // My TaskQueue_10});
TaskRouter's JS library currently raises the following events to the registered TaskQueue:
The TaskQueue has established a connection to TaskRouter and has completed initialization.
Name | Type | Description |
---|---|---|
taskQueue | TaskQueue | The created TaskQueue. |
_10taskQueue.on("ready", function(taskQueue) {_10 console.log(taskQueue.friendlyName) // My TaskQueue_10});
The TaskQueue has established a connection to TaskRouter.
_10taskQueue.on("connected", function() {_10 console.log("Websocket has connected");_10});
The TaskQueue has disconnected a connection from TaskRouter.
_10taskQueue.on("disconnected", function() {_10 console.log("Websocket has disconnected");_10});
Raised when the TaskRouter capability token used to create this TaskQueue expires.
_10taskQueue.on("token.expired", function() {_10 console.log("updating token");_10 var token = refreshJWT(); // your method to retrieve a new capability token_10 taskQueue.updateToken(token);_10});