Skip to content

Close Conversation Starter chat programmatically

When the Flow has the Add Conversation Starters (RWC) Step, its chat is a parent to the Starter chats. So users can open the Starter chats from the parent chat. Users can also close the Starter chat by clicking the Return button () either in the Starter chat itself or in the browser. This is a default behavior. However, if you need the chat to close itself instead of the user, follow the guide below.

To programmatically close the Starter chat, you need to notify the parent chat to close it. Use the following JavaScript code for the Starter chat to post a message to the window of the parent chat:

js
window.parent.postMessage({ type: 'CLOSE_STARTER' }, '*');
window.parent.postMessage({ type: 'CLOSE_STARTER' }, '*');

Close the Starter chat programmatically when its conversation ends

In this use case example, we are going to listen to the conversation end. Let's use a built-in sessions@end event provided by the RWC SDK. It is fired when a conversation ends. Upon catching this event, you can send the postMessage() event to the parent chat from the Starter chat and notify to close it. Use the following JavaScript code:

js
// wait for events in this chat
window.RWC.on('message', (data = {}) => {
  const {
    type = null
  } = data?.result?.resolve ?? {};

  switch(type) {
    // check if event is session end
    case 'sessions@end': {
      // send post message event to the parent chat so it will close THIS starter chat
      window.parent.postMessage({ type: 'CLOSE_STARTER' }, '*');

      return;
    }
  }
});
// wait for events in this chat
window.RWC.on('message', (data = {}) => {
  const {
    type = null
  } = data?.result?.resolve ?? {};

  switch(type) {
    // check if event is session end
    case 'sessions@end': {
      // send post message event to the parent chat so it will close THIS starter chat
      window.parent.postMessage({ type: 'CLOSE_STARTER' }, '*');

      return;
    }
  }
});

Where to place the code in the Flow

Place the code where you want the logic for ending the conversation to be. Make sure to place it in the Flow above the end of the Starter chat conversation. Otherwise, the event will not be handled.

This code should be executed on the frontend. You can add it to one of the following places in the Flow:

  • In the Send JavaScript Code(RWC) Step template, the Code field.
  • In the Request Response (RWC) Step template, the Custom template user input component, the JavaScript field.
  • In the Wait for Chat (RWC) Step, in the Advanced settings, enable the Extend page <head> by custom template toggle and add the code to the HTML template field.