Anthony Chu Contact Me

Embed the Bot Framework Web Chat as a Collapsible Window

Monday, September 19, 2016

Microsoft's Bot Framework is awesome. It provides a really easy way to build a chat bot and connect it to many channels including Slack, Skype, and Facebook. The Bot Framework also provides an easy way to embed a chat widget on a web page. But it embeds as an iframe, so it doesn't behave like a typical chat widget that sticks to the bottom of the browser window and pops up and down when clicked.

During a recent hackathon, my team wanted to embed the Bot Framework web chat window with stick-to-bottom and and popup/collapse functionality. We managed to do this using a script and some CSS.

popup

Here's the script:

(function () {
    var div = document.createElement("div");
    document.getElementsByTagName('body')[0].appendChild(div);
    div.outerHTML = "<div id='botDiv' style='height: 38px; position: fixed; bottom: 0; z-index: 1000; background-color: #fff'><div id='botTitleBar' style='height: 38px; width: 400px; position:fixed; cursor: pointer;'></div><iframe width='400px' height='600px' src='BOTFRAMEWORK_WEB_EMBED_URL'></iframe></div>"; 

    document.querySelector('body').addEventListener('click', function (e) {
        e.target.matches = e.target.matches || e.target.msMatchesSelector;
        if (e.target.matches('#botTitleBar')) { 
            var botDiv = document.querySelector('#botDiv'); 
            botDiv.style.height = botDiv.style.height == '600px' ? '38px' : '600px';
        };
    });
}());

It's pretty straight forward. We're injecting the iframe that came from the Bot Framework and wrapping it in a div. The div is made sticky to the bottom of the browser window (position: fixed; bottom: 0).

We're also setting the height of the div to 38px, which is the height of the web chat widget's title bar. That essentially collapses the widget when it first loads.

In order to make the widget's title bar clickable, we placed a transparent div (with an id of botTitleBar) over the title bar in the iframe and attached a click handler to it. The click handler simply toggles the height of the div. Easy!