Menu

Rate this page:

Thanks for rating this page!

We are always striving to improve our documentation quality, and your feedback is valuable to us. How could this documentation serve you better?

TaskRouter.js 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?

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

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

<script type="text/javascript" src="//media.twiliocdn.com/taskrouter/js/v1.13/taskrouter.min.js"></script>

Creating a TaskRouter Worker capability token

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):

Capability Authorization
ActivityUpdates A worker can update its current Activity.
ReservationUpdates A 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:

Loading Code Sample...
      
      
      
      

      Additionally, you can to define more granular access to particular resources beyond these capabilities. These can 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:

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

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

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

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

      Worker API

      TaskRouter.js Worker exposes the following API:

      Twilio.TaskRouter.Worker

      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)

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

      Parameters

      Name Type Description
      workerToken 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.
      connectActivitySid String (optional) ActivitySid to place the worker in upon the WebSocket Connecting
      disconnectActivitySid String (optional) ActivitySid to place the worker in upon the Websocket Disconnecting
      closeExistingSessions Boolean (optional) Whether or not to disconnect existing websockets for the same Worker upon Connecting. Defaults to false.

      Sample usage

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

      Turning off debugging:

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

      Adding Connecting and Disconnecting Activities, and closing Existing Sessions

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

      Methods

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

      Updates properties of a Worker. There are properties of a Worker, such as ActiveSid, FriendlyName, etc. These can be edited signally (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.

      Note: 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
      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 Worker object.
      Single Attribute Example
      worker.update("ActivitySid", "WAxxx", function(error, worker) {
        if(error) {
          console.log(error.code);
          console.log(error.message);
        } else {
          console.log(worker.activityName); // "Offline"
        }
      });
      
      Multiple Attribute Example
      var props = {"ActivitySid":"WAxxx", "FriendlyName":"UpdatedWorker"};
      worker.update(props, function(error, worker) {
        if(error) {
          console.log(error.code);
          console.log(error.message);
        } else {
          console.log(worker.activityName); // "Offline"
        }
      });
      

      updateToken(workerToken)

      Updates the TaskRouter capability token for the Worker.

      Parameters
      Name Type Description
      workerToken String A valid TaskRouter capability token.
      Example
      var token = refreshJWT(); // your method to retrieve a new capability token
      worker.updateToken(token);
      

      activities.fetch(callback)

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

      Parameters
      Name Type Description
      callback Function A 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
      worker.activities.fetch(
          function(error, activityList) {
              if(error) {
                  console.log(error.code);
                  console.log(error.message);
                  return;
              }
              var data = activityList.data;
              for(i=0; i<data.length; i++) {
                  console.log(data[i].friendlyName);
              }
          }
      );
      

      fetchReservations(callback)

      Retrieves the list of Reservations assigned to your Worker

      Parameters
      Name Type Description
      callback Function A 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
      params Object (optional) A JSON object of query parameters
      worker.fetchReservations(
          function(error, reservations) {
              if(error) {
                  console.log(error.code);
                  console.log(error.message);
                  return;
              }
              var data = reservations.data;
              for(i=0; i<data.length; i++) {
                  console.log(data[i].sid);
              }
          }
      );
      

      The following will fetch just pending reservations:

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

      fetchChannels(callback)

      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.

      Parameters
      Name Type Description
      callback Function A 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
      worker.fetchChannels(
          function(error, channels) {
              if(error) {
                  console.log(error.code);
                  console.log(error.message);
                  return;
              }
              var data = channels.data;
              for(i=0; i<data.length; i++) {
                  console.log(data[i].taskChannelUniqueName + " with capacity: " + data[i].configuredCapacity);
              }
          }
      );
      

      updateTask(taskSid, params, callback)

      Updates a given Task with the given parameters

      Parameters
      Name Type Description
      taskSid String The given TaskSid
      params JSON JSON object containing multiple values
      callback Function 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.
      var params = {"Priority":"15"};
      worker.updateTask(taskSid, params,
          function(error, updatedTask) {
              if(error) {
                  console.log(error.code);
                  console.log(error.message);
                  return;
              }
              console.log("Updated Task Priority: "+updatedTask.priority);
          }
      );
      

      completeTask(taskSid, callback, reason)

      Completes a given Task with an optional reason

      Parameters
      Name Type Description
      taskSid String The given TaskSid
      callback Function 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.
      reason String (optional) The reason for completion
      worker.completeTask(taskSid, 
          function(error, completedTask) {
              if(error) {
                  console.log(error.code);
                  console.log(error.message);
                  return;
              }
              console.log("Completed Task: "+completedTask.assignmentStatus);
          }
      );
      

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

      Parameters
      Name Type Description
      callback Function (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.
      reason String (optional) The reason for completion
      reservation.task.complete();
      

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

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

      on(event, callback)

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

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

      Example

      worker.on("activity.update", function(worker) {
          console.log(worker.activityName)   // 'Reserved'
          console.log(worker.activitySid)    // 'WAxxx'
          console.log(worker.available)      // false
      });
      

      Events

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

      ready

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

      Parameters

      Name Type Description
      worker Worker The Worker object for the Worker you've created.

      Example

      worker.on("ready", function(worker) {
        console.log(worker.available)       // true
      });
      

      activity.update

      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.

      Parameters

      Name Type Description
      worker Worker The updated Worker object

      Example

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

      attributes.update

      The Worker's attributes have been updated.

      Parameters

      Name Type Description
      worker Worker The updated Worker object

      Example

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

      capacity.update

      The Worker's Capacity have been updated.

      Parameters

      Name Type Description
      channel WorkerChannel The updated WorkerChannel object

      Example

      worker.on("capacity.update", function(channel) {
          console.log(channel.sid)                         // 'WCxxx'
          console.log(channel.taskChannelUniqueName)       // 'ipm'
          console.log(channel.available)                   // true
          console.log(channel.configuredCapacity)          // '3'
          console.log(channel.availableCapacityPercentage) // 66.7
          console.log(channel.assignedTasks)               // 2
      });
      

      reservation.created

      The Worker has been assigned a reservation.

      Parameters

      Name Type Description
      reservation Reservation The Reservation object that has been assigned to the Worker.

      Example

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

      worker.on("reservation.created", function(reservation) {
          console.log(reservation.task.attributes)      // {foo: 'bar', baz: 'bang' }
          console.log(reservation.task.priority)        // 1
          console.log(reservation.task.age)             // 300
          console.log(reservation.task.sid)             // WTxxx
          console.log(reservation.sid)                  // WRxxx
      });
      

      reservation.accepted

      Raised when the Worker has accepted a Reservation.

      Parameters

      Name Type Description
      reservation Reservation The Reservation object that has been accepted for this worker.

      Example

      worker.on("reservation.accepted", function(reservation) {
          console.log(reservation.task.attributes)      // {foo: 'bar', baz: 'bang' }
          console.log(reservation.task.priority)        // 1
          console.log(reservation.task.age)             // 300
          console.log(reservation.task.sid)             // WTxxx
          console.log(reservation.sid)                  // WRxxx
      });
      

      reservation.rejected

      Raised when the Worker has rejected a Reservation

      Parameters

      Name Type Description
      reservation Reservation The Reservation object that has been rejected for this worker.

      Example

      worker.on("reservation.rejected", function(reservation) {
          console.log(reservation.task.attributes)      // {foo: 'bar', baz: 'bang' }
          console.log(reservation.task.priority)        // 1
          console.log(reservation.task.age)             // 300
          console.log(reservation.task.sid)             // WTxxx
          console.log(reservation.sid)                  // WRxxx
      });
      

      reservation.timeout

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

      Parameters

      Name Type Description
      reservation Reservation The Reservation object that has been timed-out for this worker.

      Example

      worker.on("reservation.timeout", function(reservation) {
          console.log(reservation.task.attributes)      // {foo: 'bar', baz: 'bang' }
          console.log(reservation.task.priority)        // 1
          console.log(reservation.task.age)             // 300
          console.log(reservation.task.sid)             // WTxxx
          console.log(reservation.sid)                  // WRxxx
      });
      

      reservation.canceled

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

      Parameters

      Name Type Description
      reservation Reservation The Reservation object that has been canceled for this worker.

      Handling reservation being canceled

      worker.on("reservation.canceled", function(reservation) {
          console.log(reservation.task.attributes)      // {foo: 'bar', baz: 'bang' }
          console.log(reservation.task.priority)        // 1
          console.log(reservation.task.age)             // 300
          console.log(reservation.task.sid)             // WTxxx
          console.log(reservation.sid)                  // WRxxx
      });
      

      reservation.rescinded

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

      Parameters

      Name Type Description
      reservation Reservation The Reservation object that has been rescinded for this worker.

      Handling reservation being rescinded

      worker.on("reservation.rescinded", function(reservation) {
          console.log(reservation.task.attributes)      // {foo: 'bar', baz: 'bang' }
          console.log(reservation.task.priority)        // 1
          console.log(reservation.task.age)             // 300
          console.log(reservation.task.sid)             // WTxxx
          console.log(reservation.sid)                  // WRxxx
      });
      

      token.expired

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

      Example

      worker.on("token.expired", function() {
          console.log("updating token");
          var token = refreshJWT(); // your method to retrieve a new capability token
          worker.updateToken(token);
      });
      

      connected

      Example

      Raised when the Websocket connects.

      worker.on("connected", function() {
        console.log("Websocket has connected");
      });
      

      disconnected

      Example

      Raised when the Websocket disconnects.

      worker.on("disconnected", function() {
        console.log("Websocket has disconnected");
      });
      

      error

      Raised when the Websocket has an error.

      Example

      worker.on("error", function(error) {
          console.log("Websocket had an error: "+ error.response + " with message: "+error.message);
      });
      

      Reservation Actions

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

      reservation.accept

      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.

      Parameters

      Name Type Description
      resultCallback Function (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.
      reservation.accept(
          function(error, reservation) {
              if(error) {
                  console.log(error.code);
                  console.log(error.message);
                  return;
              }
              console.log("reservation accepted");
              for (var property in reservation) {
                  console.log(property+" : "+reservation[property]);
              }
          }
      );
      

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

      reservation.accept();
      

      reservation.reject

      This will reject the reservation for the worker.

      Parameters

      Name Type Description
      activitySid String (optional) The activitySid to update the worker to after rejecting the reservation
      resultCallback Function (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.
      reservation.reject(
          function(error, reservation) {
              if(error) {
                  console.log(error.code);
                  console.log(error.message);
                  return;
              }
              console.log("reservation rejected");
              for (var property in reservation) {
                  console.log(property+" : "+reservation[property]);
              }
          }
      );
      

      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");
      

      reservation.conference

      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.

      Parameters

      Name Type Description
      from String (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.
      postWorkActivitySid String (optional) The activitySid to update the worker to after conference completes.
      timeout string (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.
      to string (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.
      resultCallback Function (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.
      options object (optional) If you have Agent Conference enabled, you can utilize all the same 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

      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:

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

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

      var options = {
          "ConferenceStatusCallback": "https://requestb.in/wzfljiwz",
          "ConferenceStatusCallbackEvent": "start,end",
          "ConferenceRecord": "true", 
          "ConferenceRecordingStatusCallback": "https://requestb.in/wzfljiwz",
          "EndConferenceOnExit": "true"
      }
      
      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:

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

      reservation.dequeue

      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.

      Parameters

      Name Type Description
      dequeueFrom String (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.
      dequeuePostWorkActivitySid String (optional) The activitySid to update the worker to after dequeuing the reservation
      dequeueRecord string (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.
      dequeueTimeout string (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.
      dequeueStatusCallbackUrl string (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.
      dequeueStatusCallbackEvents string (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.
      dequeueTo string (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.
      resultCallback Function (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:

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

      reservation.call

      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.

      Parameters

      Name Type Description Calls API Parameter
      callFrom String The caller id for the call to the worker From
      callUrl String A valid TwiML URI that is executed on the answering Worker's leg. Url
      callStatusCallbackUrl String (optional) A valid status callback url. StatusCallback
      callAccept String (optional) "true" or "false", accept the task before initiating call. Defaults to "false". Needs to be a string. Eg: "true", not true
      callRecord String (optional) record-from-answer or false. Record the call. Defaults to false. Record
      callTo String (optional) Whom to call. If not provided, will utilize worker contact_uri attribute To
      resultCallback Function (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.
      reservation.call(
          "18004746453",
          "http://twimlbin.com/451369ae",
          "http://requestb.in/13285vq1",
          "true",
          "record-from-answer",
          "client:joey"
          function(error, reservation) {
              if(error) {
                  console.log(error.code);
                  console.log(error.message);
                  return;
              }
              console.log("reservation called the worker");
          }
      );
      

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

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

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

      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:

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

      reservation.redirect

      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.

      Parameters

      Name Type Description Calls API Parameter
      redirectCallSid String The Call to Redirect From
      redirectUrl String A valid TwiML URI that is executed on the Caller's leg upon redirecting. Url
      redirectAccept String (optional) "true" or "false", accept the task before initiating call. Defaults to "false". Needs to be a string. Eg: "true", not true
      resultCallback Function (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.
      reservation.redirect(
          "CAxxxx",                //redirectCallSid
          "https://handler.twilio.com/twiml/EH621f0e21da7ce5441f6ec6aacce64069",    //redirectUrl
          "true",        //redirectAccept
          function(error, reservation) {        //resultCallback
              if(error) {
                  console.log(error.code);
                  console.log(error.message);
                  return;
              }
              console.log("reservation call was redirected");
          }
      );
      

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

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

      Need some help?

      We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd browsing the Twilio tag on Stack Overflow.

      Loading Code Sample...