Question
I want to modify the native behavior of the Web Widget (Classic) using Javascript APIs. I read through the Help Center and I found many different implementations. How can I combine these different Web Widget (Classic) API workflows?
Answer
The most important thing to be aware of is when you want to have your widget settings applied. Some workflows need to be run whenever a department is updated, while others need to be run when the widget first connects or reconnects. This is illustrated with this simplified example of setting the CRM department:
<script id="ze-snippet"
src="https://static.zdassets.com/ekr/snippet.js?key=ACCOUNT_KEY"> </script>
<script>
// first hide the widget on page load
zE('webWidget', 'hide');
// whenever an unread message appears unhide and open the widget
zE('webWidget:on', 'chat:unreadMessages', function(number) {
zE('webWidget', 'show');
zE('webWidget', 'open');
});
// this callback runs whenever chat first connects (or reconnects)
zE('webWidget:on', 'chat:connected', function() {
// put any code you only want run once here
});
// this callback runs whenever a department status changes
zE('webWidget:on', 'chat:departmentStatus', function(dept) {
// only set the widget online for chat if this department was online
if (dept.name === 'CRM' && dept.status === 'online') {
// apply the chat widget settings
zE('webWidget', 'updateSettings', {
webWidget: {
chat: {
departments: {
enabled: [''],
select: 'CRM'
},
suppress: false
}
}
});
} else if (dept.name === 'CRM' && dept.status !== 'online') {
// or suppress chat (optional: apply contact form settings here)
zE('webWidget', 'updateSettings', {
webWidget: {
chat: {
suppress: true
}
}
});
}
});
</script>
There's a couple of things in the above script worth discussing. First, the initial steps of hiding the widget and then showing it when an unread message is received could be omitted completely without changing the rest of the script's functionality. Given that they are being used as soon as the widget is loaded, they were placed at the top of the script. This is not strictly necessary.
Next, it is worth noting that while some custom workflows place a updateSettings API block in a chat:connected callback, you are also able to put this in a chat:departmentStatus, and it will also be applied when the widget first connects (or reconnects after a timed-out session). For this reason, use the chat:connected
API specifically for commands you only wish to fire once, and the chat:departmentStatus
API for commands you want to fire anytime the specified department changes after the page loads.
For more information on different Web Widget (Classic) API workflows, see these articles: