I couldn't see a native method in the Chat Widget SDK to check if the chat widget is closed. However, I came up with this script (perhaps the not most elegant solution), which listens for the user's first click into the iframe chat widget and then keeps checking the value stored in the hs-messages-is-open cookie until it is false. When the value is false it means the user has closed the chat widget and the widget is removed from the page and the script stops checking the cookie.
<script>
// listen every 100 ms for first iframe click
var monitorFrame = setInterval(function () {
var elem = document.activeElement;
if (elem && elem.tagName == 'IFRAME') {
clearInterval(monitorFrame);
// Keep checking cookie value every 100 ms for first iframe click
var monitorCookie = setInterval(function () {
// Get hs-messages-is-open value
function getCookie(name) {
var re = new RegExp(name + "=([^;]+)");
var value = re.exec(document.cookie);
return (value != null) ? unescape(value[1]) : null;
}
var cookieVal = getCookie("hs-messages-is-open");
// If cookie value is false remove the chat widget and clear 100 ms listener
if (cookieVal == "false") {
window.HubSpotConversations.widget.remove();
clearInterval(monitorCookie);
}
}, 100);
}
}, 100);
</script>
Matthew Shepherd
Freelance HubSpot Consultant CRM Consultant | SEO Specialist
The onclick="window.HubSpotConversations.widget.open();" method will only open a chatflow that has been configured to target your page and is enabled, so it is expected behaviour that this won't work when you turn the chatflow off.
I believe the solution offered by @WendyGohin this post may be a solution for your use case:
Set your chat widget to target Query Parameter bot is true
This means your chat widget won't load until that URL parameter is detected in the page being viewed. You could then just make the href in your link to open the chat widget videoworks.com?bot=true, but that will make the page reload. To avoid this you can make your link's onclick something like this: