Skip to main contentWatson Assistant web chat

Session history

Learn how to work with session history so that your user's conversations will continue seamlessly across page changes and reloads.

Overview

Session history allows your web chats to maintain conversation history and context when customers refresh the page or change to a different page on the same website.

The conversation history lasts until the session times out, and it persists within only one browser tab; opening a new tab starts a new session. This feature only maintains conversations between customers and assistants, not customers and human agents.

Session history is now generally available and enabled by default. If you were using the "sessionHistoryBeta" feature flag in version 3.5.0, that can now be removed from your embed script.

Tutorial 1: Controlling link behavior

Session history persists within only one browser tab, not across multiple tabs. In the dialog, we give you control over whether the link should open in a new tab or the same tab.

Example 1: The default behavior is for links to open in a new tab. If you copy and paste the following snippet into a text response in your dialog, the web chat will show "Click this default link that will open in a new tab: https://www.ibm.com/cloud/watson-assistant"

'Click this default link that will open in a new tab: https://www.ibm.com/cloud/watson-assistant'

Example 2: If you want to change the behavior so that links open in the same tab, simply copy and paste the following snippet into a text response in your dialog. In this case the web chat will show "Click this link that will open in the same tab: link"

'Click this link that will open in the same tab: <a href="https://www.ibm.com/cloud/watson-assistant">link</a>'

Example 3: If you want to lock your link to always open in a new tab, copy and paste the following snippet into a text response in your dialog. In this case the web chat will show "Click this link that will open in the same tab: link"

'Click this link that is forced to open in a new tab: <a href="https://www.ibm.com/cloud/watson-assistant" target="_blank">link</a>'

Because session history persists within only one browser tab,Example 2 is generally preferred for cases where links point to other areas of your website where the web chat is in use. That way your users are able to continue their conversations with web chat on the new page your link sends them to. However, if you have links in your dialog that go to external sites, or parts of your site where the web chat isn't being used, Example 1 or Example 3 is preferred. That way your users' conversations with the web chat can stay active on the previous tab.

Tutorial 2: Saving the state of custom responses in history

If you are not customizing the web chat with the customResponse or pre:receive events, then you're all set with session history the way it is enabled by default, and you don't need to follow the rest of this tutorial. If you are using these customizations, there are a few events and methods to be aware of:

First, there are events that indicate that the history is beginning to reload and that the history is completing its reload; these events are history:begin and history:end. These events can be used to view the messages that are being reloaded, and in the case of history:begin, the messages can be edited before they are displayed.

Second, there have been changes made to pre:receive. Pre:receive now includes a flag that is enabled by default: event.updateHistory. This flag tells the web chat whether it should save the original message that existed before changes were made in pre:receive or save the new message that is created by the edits in pre:receive. If the flag is left as truethen the message will be saved with the pre:receive edits and re-rendered on page change or reload exactly as it looked before.

Third, there is now an instance method available to enable saving of state related to a specific message response: instance.updateHistoryUserDefined(). With the state saved a response can be re-rendered with the same state that it was initially rendered with. For an example of this, see the "Example with session history" in the customResponse section.

The next section provides a deeper dive into using the instance.updateHistoryUserDefined() function as we show you how to save the state of custom response types in history.

Example

This tutorial builds on the Custom response types tutorial and shows you how to save the state of your custom response types in history. To try out the tutorial, open the web chat, select "Let me set the color of some text", type in a new color and hit enter, refresh the page, and then marvel at the fact that the color is saved on refresh.


<!doctype html>
<html lang="en">

<body>
  <script>
  /**
   * Renders a custom response by showing some text and an input field.
   */
  function customResponseHandlerWithSessionHistory(event, instance) {
    const { message } = event.data;
  
    const textElement = document.createElement('p');
    textElement.innerText = 'Type in a color below and hit enter to change the color of this text.';
  
    const textStyle = 'color: black; margin-top: 0;';
    textElement.setAttribute('style', textStyle);
  
    const inputElement = document.createElement('input');
    inputElement.setAttribute('type', 'text');
  
    // If there's history for this message then lets use the color we saved to start.
    if(event.data.fullMessage.history && event.data.fullMessage.history.user_defined && event.data.fullMessage.history.user_defined.color) {
      inputElement.setAttribute('value', event.data.fullMessage.history.user_defined.color);  
    } else {
      inputElement.setAttribute('value', message.user_defined.default_color);
    }
    textElement.style.color = inputElement.value;
  
    inputElement.addEventListener('change', function inputChange() {
      textElement.style.color = inputElement.value;
      // After we've updated the elements color lets save the color in history so we can use it on reload.
      instance.updateHistoryUserDefined(event.data.fullMessage.id, {color: inputElement.value});
    });
  
    const footerElement = document.createElement('p');
    footerElement.innerText = 'Because of session history the color you have set will still be set after the page is refreshed.';
  
    const divElement = document.createElement('div');
    divElement.setAttribute('style', 'padding-bottom: 24px;');
    divElement.appendChild(textElement);
    divElement.appendChild(inputElement);
    divElement.appendChild(footerElement);
  
    event.data.element.appendChild(divElement);
  }

    window.watsonAssistantChatOptions = {
      integrationID: "YOUR_INTEGRATION_ID",
      region: "YOUR_REGION",
      serviceInstanceID: "YOUR_SERVICE_INSTANCE_ID",
      onLoad: function (instance) {
        /**
         * See the "Custom response types" tutorial for more info on how to set up a customResponse handler like this.
         * Watch for the customResponse event and forward incoming data to the correct handler.
        */
        function customResponseHandler(event) {
          const { message } = event.data;
          // Add a switch so you can watch for different custom responses.
          switch (message.user_defined.template_name) {
            case 'color_box':
              customResponseHandlerWithSessionHistory(event, instance);
              break;
            default:
              console.error('Unhandled response type.');
          }
        }
        // Watch for the customResponse event to handle the user defined response type.
        instance.on({
          type: "customResponse",
          handler: customResponseHandler
        });
        instance.render();
      }
    };
    setTimeout(function () {
      const t = document.createElement('script');
      t.src="https://web-chat.global.assistant.watson.appdomain.cloud/loadWatsonAssistantChat.js";
      document.head.appendChild(t);
    });
  </script>
</body>

</html>

This preconfigured code snippet is just an example of some ways to edit messages and then save their edited state so they can be re-rendered correctly after page changes or reloads.