Controlling the Widget

If you want to customize the Drift widget beyond what is offered through the Drift application, you can use JavaScript to control aspects of our widget manually. Below are some examples of controlling the widget, and more detailed documentation can be found here.

Initializing the Drift Widget

The ready event indicates that Drift widget is ready for use. It contains a single argument which is the actual API object that can then be acted upon.

Note:

This script should live inside your <head></head> section on your webpage.
It should also always come after the Javascript snippet you copy pasted to install Drift.

<script> 
drift.on('ready',function(api, payload) {
 // interact with the api here
})
</script>
<script> 
analytics.ready(function(){
  drift.on('ready',function(api){
    // interact with the api here
  })
})
</script>

If you're using the Segment integration, you can still use the Drift Widget API, but the Drift object won't be immediately available in the window. You can use Segment's analytics.ready function below to determine when the Drift Api has been installed and is ready for use.

Code Example: customize widget using Widget API

The following snippet uses the hide() and show() functions and the sidebarOpen and widgetVisible events to hide the widget from users until they receive a message.

drift.on('ready',function(api){
  // hide the widget when it first loads
api.widget.hide()
 // show the widget when you receive a message
  drift.on('message',function(e){
    if(!e.data.sidebarOpen){
      api.widget.show()
    }
  })
  // hide the widget when you close the sidebar
    drift.on('sidebarClose',function(e){
      if(e.data.widgetVisible){
        api.widget.hide()
      }
    })
  })

Not using Drift yet? Get your free account here!

Controlling the Widget