Skip to contentSkip to navigationSkip to topbar
On this page

Control Worker Activities using Worker.js: Add an Agent UI to our Project


Let's get started on our agent UI. Assuming you've followed the conventions so far in this tutorial, the UI we create will be accessible using your web browser at:

http://localhost:8080/agent.php?WorkerSid=WKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX (substitute your Alice's WorkerSid)

We pass the WorkerSid in the URL to avoid implementing complex user management in our demo. In reality, you are likely to store a user's WorkerSid in your database alongside other User attributes.

First, create a file called agent.php and add the following code. Remember to substitute your own account and Workspace credentials between the curly braces:

agent.php

agentphp page anchor
1
<?php
2
// Get the Twilio-PHP library from twilio.com/docs/libraries/php,
3
// following the instructions to install it with Composer.
4
require_once "vendor/autoload.php";
5
6
// Your Account SID from www.twilio.com/console
7
// To set up environmental variables, see http://twil.io/secure
8
$accountSid = getenv('TWILIO_ACCOUNT_SID');
9
// Your Auth Token from www.twilio.com/console
10
$authToken = getenv('TWILIO_AUTH_TOKEN');
11
$workspaceSid = 'WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
12
13
$workerSid = $_REQUEST['WorkerSid'];
14
15
$workerCapability = new Twilio\Jwt\TaskRouter\WorkerCapability(
16
$accountSid, $authToken, $workspaceSid, $workerSid);
17
$workerCapability->allowActivityUpdates();
18
$workerToken = $workerCapability->generateToken();
19
20
?>
21
<!DOCTYPE html>
22
<html>
23
<head>
24
<title>Customer Care - Voice Agent Screen</title>
25
<link rel="stylesheet" href="//media.twiliocdn.com/taskrouter/quickstart/agent.css"/>
26
<script src="//media.twiliocdn.com/taskrouter/js/v1.13/taskrouter.min.js"></script>
27
<script src="agent.js"></script>
28
</head>
29
<body>
30
<div class="content">
31
<section class="agent-activity offline">
32
<p class="activity">Offline</p>
33
<button class="change-activity" data-next-activity="Idle">Go Available</button>
34
</section>
35
<section class="agent-activity idle">
36
<p class="activity"><span>Available</span></p>
37
<button class="change-activity" data-next-activity="Offline">Go Offline</button>
38
</section>
39
<section class="agent-activity reserved">
40
<p class="activity">Reserved</p>
41
</section>
42
<section class="agent-activity busy">
43
<p class="activity">Busy</p>
44
</section>
45
<section class="agent-activity wrapup">
46
<p class="activity">Wrap-Up</p>
47
<button class="change-activity" data-next-activity="Idle">Go Available</button>
48
<button class="change-activity" data-next-activity="Offline">Go Offline</button>
49
</section>
50
<section class="log">
51
<textarea id="log" readonly="true"></textarea>
52
</section>
53
</div>
54
<script>
55
window.workerToken = "<?= $workerToken ?>";
56
</script>
57
</body>
58
</html>

You'll notice that we included three external files:

  • taskrouter.min.js is the primary TaskRouter.js JavaScript file that communicates with TaskRouter's infrastructure on our behalf. You can use this URL to include TaskRouter.js in your production application, but first check the reference documentation to ensure that you include the latest version number.
  • agent.css is a simple CSS file created for the purpose of this Quickstart. It saves us having to type out some simple pre-defined styles.
  • agent.js contains our custom JavaScript logic for this application. We need to create that next, but first...

Download and extract Twilio's PHP helper library(link takes you to an external page) into the same directory that you are working in. This is required as our code references twilio-php/Services/Twilio.php. For more advanced PHP users, the composer package manager will also work fine. See the twilio-php documentation(link takes you to an external page).

Create the agent.js file in the same directory as your agent.php and add the following code:


agent.js

agentjs page anchor
1
/* Subscribe to a subset of the available Worker.js events */
2
3
function registerTaskRouterCallbacks() {
4
worker.on('ready', function(worker) {
5
agentActivityChanged(worker.activityName);
6
logger("Successfully registered as: " + worker.friendlyName)
7
logger("Current activity is: " + worker.activityName);
8
});
9
10
worker.on('activity.update', function(worker) {
11
agentActivityChanged(worker.activityName);
12
logger("Worker activity changed to: " + worker.activityName);
13
});
14
15
worker.on("reservation.created", function(reservation) {
16
logger("-----");
17
logger("You have been reserved to handle a call!");
18
logger("Call from: " + reservation.task.attributes.from);
19
logger("Selected language: " + reservation.task.attributes.selected_language);
20
logger("-----");
21
});
22
23
worker.on("reservation.accepted", function(reservation) {
24
logger("Reservation " + reservation.sid + " accepted!");
25
});
26
27
worker.on("reservation.rejected", function(reservation) {
28
logger("Reservation " + reservation.sid + " rejected!");
29
});
30
31
worker.on("reservation.timeout", function(reservation) {
32
logger("Reservation " + reservation.sid + " timed out!");
33
});
34
35
worker.on("reservation.canceled", function(reservation) {
36
logger("Reservation " + reservation.sid + " canceled!");
37
});
38
}
39
40
/* Hook up the agent Activity buttons to Worker.js */
41
42
function bindAgentActivityButtons() {
43
// Fetch the full list of available Activities from TaskRouter. Store each
44
// ActivitySid against the matching Friendly Name
45
var activitySids = {};
46
worker.activities.fetch(function(error, activityList) {
47
var activities = activityList.data;
48
var i = activities.length;
49
while (i--) {
50
activitySids[activities[i].friendlyName] = activities[i].sid;
51
}
52
});
53
54
/* For each button of class 'change-activity' in our Agent UI, look up the
55
ActivitySid corresponding to the Friendly Name in the button's next-activity
56
data attribute. Use Worker.js to transition the agent to that ActivitySid
57
when the button is clicked.*/
58
var elements = document.getElementsByClassName('change-activity');
59
var i = elements.length;
60
while (i--) {
61
elements[i].onclick = function() {
62
var nextActivity = this.dataset.nextActivity;
63
var nextActivitySid = activitySids[nextActivity];
64
worker.update({"ActivitySid":nextActivitySid});
65
}
66
}
67
}
68
69
/* Update the UI to reflect a change in Activity */
70
71
function agentActivityChanged(activity) {
72
hideAgentActivities();
73
showAgentActivity(activity);
74
}
75
76
function hideAgentActivities() {
77
var elements = document.getElementsByClassName('agent-activity');
78
var i = elements.length;
79
while (i--) {
80
elements[i].style.display = 'none';
81
}
82
}
83
84
function showAgentActivity(activity) {
85
activity = activity.toLowerCase();
86
var elements = document.getElementsByClassName(('agent-activity ' + activity));
87
elements.item(0).style.display = 'block';
88
}
89
90
/* Other stuff */
91
92
function logger(message) {
93
var log = document.getElementById('log');
94
log.value += "\n> " + message;
95
log.scrollTop = log.scrollHeight;
96
}
97
98
window.onload = function() {
99
// Initialize TaskRouter.js on page load using window.workerToken -
100
// a Twilio Capability token that was set in a <script> in agent.php
101
logger("Initializing...");
102
window.worker = new Twilio.TaskRouter.Worker(workerToken);
103
registerTaskRouterCallbacks();
104
bindAgentActivityButtons();
105
};

And that's it! Open http://localhost:8080/agent.php?WorkerSid=WK012340123401234 in your browser and you should see the screen below. If you make the same phone call as we made in Part 3, you should see Alice's Activity transition on screen as she is reserved and assigned to handle the Task.

If you see "Initializing..." and no progress, make sure that you have included the correct WorkerSid in the "WorkerSid" request parameter of the URL.

For more details, refer to the TaskRouter.js Worker JavaScript SDK documentation.


  • This simple PoC has been tested in the latest version of popular browsers, including IE 11. *
Completed Agent UI.

Need some help?

Terms of service

Copyright © 2024 Twilio Inc.