Dialogflow Messenger

This integration provides a customizable chat dialog for your agent that can be embedded in your website.

Dialogflow Messenger screenshot

Setup

This integration can allow either authenticated or unauthenticated end-user agent query access.

Unauthenticated setup

To set up unauthenticated access to your Dialogflow Messenger agent:

  1. Go to the Dialogflow CX Console.
  2. Choose your Google Cloud project.
  3. Select your agent.
  4. Select the Manage tab.
  5. Click Integrations in the left sidebar menu.
  6. Click Connect on Dialogflow Messenger.
  7. A configuration dialog opens.
  8. If the integration was previously setup for this agent, you will see embeddable HTML code. Regardless of whether you want what authenticated or unauthenticated, click the Disable... button at the bottom of the dialog, so you can reconfigure the settings in the next step.
  9. Select an Environment.
  10. Select Unauthenticated API.
  11. Select a style.
  12. Optionally restrict domain access.
  13. Click Enable the unauthenticated API.
  14. The dialog will show the embeddable HTML code that can be embedded on your website. Copy this code.
  15. Click Done.

Authenticated setup

To set up authenticated access to your Dialogflow Messenger agent:

  1. Go to the Dialogflow CX Console.
  2. Choose your Google Cloud project.
  3. Select your agent.
  4. Select the Manage tab.
  5. Click Integrations in the left sidebar menu.
  6. Click Connect on Dialogflow Messenger.
  7. A configuration dialog opens.
  8. If the integration was previously setup for this agent, you will see embeddable HTML code. Regardless of whether you want what authenticated or unauthenticated, click the Disable... button at the bottom of the dialog, so you can reconfigure the settings in the next step.
  9. Select an Environment.
  10. Select Authorized API.
  11. Select a style.
  12. Optionally restrict domain access.
  13. Click Enable the authorized API.
  14. The dialog will show the embeddable HTML code that can be embedded on your website. Copy this code.
  15. Click Done.
  16. Set up the OAuth client:
    1. Create an OAuth consent screen for your organization. Add ./auth/cloud-platform as a required scope.
    2. Create an OAuth 2.0 Client ID. Under Authorized JavaScript origins, specify the HTTP origins that are allowed to host and query your agent. For example, https://your-company.com.
    3. Provide end-users with permission to query your agent. Add each of your end-users or a group as a principal with the Dialogflow API Client role.

Embed

Paste the embed code you copied above in a webpage on your website. The <script> and <df-messenger> HTML elements should be in the <body> element of your page.

If you are using an authenticated integration, set the oauth-client-id attribute for <df-messenger> to your Oauth client id.

Update any other attributes that require updating.

To allow for responsive layouts, also add the following to your <head> element:

<meta name="viewport" content="width=device-width, initial-scale=1">

HTML chat element options

The child element of the df-messenger element can be either of:

  • df-messenger-chat: agent dialog is always open
  • df-messenger-chat-bubble: agent dialog can be opened or closed with an open/close bubble button

HTML customizations

You can customize various aspects for how the chat dialog appears and behaves.

HTML customizations for df-messenger

The df-messenger HTML element has the following attributes:

Attribute Input policy Value
agent-id Required Agent ID associated with the Dialogflow agent.
allow-feedback Optional Set to all to allow end-users to provide feedback on the agent's answers.
language-code Required Default language code.
project-id Required Project ID for the agent.
location Optional The agent's region. Default value is global.
intent Optional A custom event that will be invoked when the chat dialog is opened. You can use an event handler that will be called for this event and will produce the first agent message.
oauth-client-id Optional Required for OAuth authentication. Default value is null. If the value is not provided and Dialogflow Messenger unauthenticated access is enabled, unauthenticated users can interact with the agent. If the value is provided, the agent dialog will be overlaid with a "Request Authentication" (text can be controlled, see request-auth-text below) notification, which requires the user to sign in before they can use the agent.
storage-option Optional Specifies local storage for conversation messages. Use none if messages should not be stored. Using none will clear all messages when the page is refreshed or reloaded. Defaults to sessionStorage.
session-ttl Optional Set to a duration in seconds to maintain session, must be strictly below 86400 (1d) and defaults to 1800 (30min).
url-allowlist Optional Enables images being loaded from a comma separated list of URL prefixes. Image URLs used in HTML or Markdown responses must start with one of the listed prefixes. Use * to allow all URLs.

HTML customizations for df-messenger-chat

Dialogflow Messenger screenshot

The df-messenger-chat HTML element has the following attributes:

Attribute Input policy Value
chat-title Optional The title of the chat box, shown above it.
chat-subtitle Optional The subtitle of the chat box, shown above it, below the chat-title
chat-title-icon Optional The icon shown in the title of the chat box, shown above it, left of the chat-title by default
bot-writing-text Optional The text that is shown while the agent is writing
bot-writing-image Optional The image that is shown while the agent is writing. Takes priority over bot-writing-text.
request-auth-text Optional The button text in case authentication is required.
placeholder-text Optional Text to be shown in the input field while it's empty. Defaults to "Ask something…".

HTML customizations for df-messenger-chat-bubble

Dialogflow Messenger screenshot

The df-messenger-chat-bubble HTML element has the same attributes as df-messenger-chat and the following additional attributes:

Attribute Input policy Value
expanded Optional Boolean that determines whether the chat is initially open. If not set, the chat will remember its last state.
chat-icon Optional The icon for the chat bubble. Must be a publicly available URI.
chat-close-icon Optional The close icon for the chat bubble. Must be a publicly available URI.
chat-collapse-icon Optional The icon for the collapse button in the title bar. Must be a publicly available URI.
anchor Optional Defines where the chat dialog is placed relative to the open or close bubble. The value is two direction words (top, bottom, left, right) delimited by -. Default value is top-left. The first direction defines the anchoring point, and the second direction defines the main expansion direction away from the bubble. For example: top-left is placed on top of the bubble and expands to the left and upward (away from the bubble).
chat-width Optional Defines the width of the chat window. Numerical values (in pixel). Defaults to 320px.
chat-height Optional Defines the height of the chat window. Numerical values (in pixel). Defaults to 480px.
allow-fullscreen Optional Defines if the chat window can open fullscreen. If set to always, opens in fullscreen for all screen sizes. If set to small, opens fullscreen for screen sizes below 500px, otherwise opens as a normal window. May override chat-width, chat-height and anchor if set.

CSS customizations

You can customize the style of your chat dialog by setting CSS variables.

General styling

The following CSS variables provide general styling options:

Properties Input policy Default value Description
df-messenger-font-family Optional "Google Sans", "Helvetica Neue", sans-serif Font family to use throughout the widget
df-messenger-font-size Optional 14px Text size to use throughout the widget
df-messenger-font-color Optional #1f1f1f Text color to use throughout the widget
df-messenger-primary-color Optional #0b57d0 Primary color for elements throughout the widget (such as title bar background, action button background and more)
df-messenger-focus-color Optional #1e88e5 Color of the focus ring around elements
df-messenger-focus-color-contrast Optional white Color of the focus ring around elements when inside a parent with a background color (such as the title bar)
df-messenger-chat-border Optional none Border for the dialog
df-messenger-chat-border-radius Optional 0 Border radius for the dialog

Styling for df-messenger-chat-bubble

When using the df-messenger-chat-bubble element, the following CSS variables can be provided:

Properties Input policy Default value Description
df-messenger-chat-window-height Optional 480px Height of the chat window
df-messenger-chat-window-width Optional 320px Width of the chat window
df-messenger-chat-window-offset Optional 16px Distance between the chat bubble and the chat window
df-messenger-chat-window-box-shadow Optional none Box shadow of the chat window
df-messenger-chat-bubble-close-icon-size Optional 24px Size of the close icon for the chat bubble
df-messenger-chat-collapse-icon-size Optional unset Size of the collapse button icon in the title bar
df-messenger-chat-bubble-close-icon-transform-rotate Optional -90deg Rotation of the close icon for the chat bubble, rotates to 0deg on closing the chat
df-messenger-chat-bubble-size Optional 64px Size of the chat bubble
df-messenger-chat-bubble-border-radius Optional 32px Border radius of the chat bubble
df-messenger-chat-bubble-border Optional none Border of the chat bubble

Styling for titlebar

For the titlebar, the following CSS variables can be provided:

Properties Input policy Default value Description
df-messenger-titlebar-background Optional #0b57d0 Background of the title bar
df-messenger-titlebar-padding Optional 0 15px Padding of the title bar
df-messenger-titlebar-border Optional none Border for the title bar
df-messenger-titlebar-border-bottom Optional none Border bottom of the title bar
df-messenger-titlebar-title-align Optional start Text alignment of the title text(s) in the title bar, allowed values are start, center or end
df-messenger-titlebar-font-color Optional white Text color of the text in the title bar
df-messenger-titlebar-letter-spacing Optional normal Letter spacing of the text in the title bar
df-messenger-titlebar-title-font-size Optional 18px Text size of the title text in the title bar
df-messenger-titlebar-title-font-family Optional "Google Sans", "Helvetica Neue", sans-serif Font family of the title text in the title bar
df-messenger-titlebar-title-font-weight Optional 400 Font weight of the title text in the title bar
df-messenger-titlebar-title-line-height Optional normal Line height of the title text in the title bar
df-messenger-titlebar-title-letter-spacing Optional normal Letter spacing of the title text in the title bar
df-messenger-titlebar-subtitle-font-color Optional white Text color of the subtitle text in the title bar
df-messenger-titlebar-subtitle-font-size Optional 18px Text size of the subtitle text in the title bar
df-messenger-titlebar-subtitle-font-family Optional "Google Sans", "Helvetica Neue", sans-serif Font family of the subtitle text in the title bar
df-messenger-titlebar-subtitle-font-weight Optional 400 Font weight of the subtitle text in the title bar
df-messenger-titlebar-subtitle-line-height Optional normal Line height of the subtitle text in the title bar
df-messenger-titlebar-subtitle-letter-spacing Optional normal Letter spacing of the subtitle text in the title bar
df-messenger-titlebar-title-order Optional row Order elements in the title bar, allowed values are row or row-reverse. This value is only effective if the chat-title-icon attribute has been specified.
df-messenger-titlebar-icon-width Optional 18px The width of the icon in the title bar. This value is only applied if the chat-title-icon has been specified.
df-messenger-titlebar-icon-height Optional 18px The height of the icon in the title bar. This value is only applied if the chat-title-icon has been specified.
df-messenger-titlebar-icon-padding Optional 0 12px 0 0 The padding around the icon in the title bar. This value is only applied if the chat-title-icon has been specified.

Styling for chat window

For the chat window, the following CSS variables can be provided:

Properties Input policy Default value Description
df-messenger-chat-background Optional #fafafa Background of the agent dialog where messages are shown
df-messenger-chat-padding Optional 10px Padding of the agent dialog where messages are shown
df-messenger-messagelist-border Optional none Border of the message list
df-messenger-message-border Optional none Border of the agent dialog messages
df-messenger-message-font-size Optional 14px Text size of the agent dialog messages
df-messenger-message-font-family Optional "Google Sans", "Helvetica Neue", sans-serif Font family of the agent dialog messages
df-messenger-message-font-weight Optional normal Font weight of the agent dialog messages
df-messenger-message-bot-background Optional #ecf3fe Background of the messages sent by the agent
df-messenger-message-bot-border Optional none Border of the messages sent by the agent
df-messenger-message-bot-font-color Optional #1f1f1f Text color of the messages sent by the agent
df-messenger-message-bot-font-weight Optional normal Font weight of the messages sent by the agent
df-messenger-message-user-background Optional #e1e3e1 Background of the messages sent by the user
df-messenger-message-user-border Optional none Border of the messages sent by the user
df-messenger-message-user-font-color Optional #1f1f1f Text color of the messages sent by the user
df-messenger-message-user-font-weight Optional normal Font weight of the messages sent by the user
df-messenger-feedback-font-color Optional #333333 Text color of the feedback buttons
df-messenger-feedback-spacing Optional 10px Space between the last message and the feedback buttons
df-messenger-message-spacing Optional 10px Space between two messages
df-messenger-message-border-radius Optional 8px Border radius for messages, applies to all corners
df-messenger-message-bot-border-top-left-radius Optional 8px Border radius top left for agent messages, overrides generic radius
df-messenger-message-bot-border-top-right-radius Optional 8px Border radius top right for agent messages, overrides generic radius
df-messenger-message-bot-border-bottom-left-radius Optional 8px Border radius bottom left for agent messages, overrides generic radius
df-messenger-message-bot-border-bottom-right-radius Optional 8px Border radius bottom right for agent messages, overrides generic radius
df-messenger-message-user-border-top-left-radius Optional 8px Border radius top left for user messages, overrides generic radius
df-messenger-message-user-border-top-right-radius Optional 8px Border radius top right for user messages, overrides generic radius
df-messenger-message-user-border-bottom-left-radius Optional 8px Border radius bottom left for user messages, overrides generic radius
df-messenger-message-user-border-bottom-right-radius Optional 8px Border radius bottom right for user messages, overrides generic radius
df-messenger-message-stack-spacing Optional 10px Space between two consecutive messages
df-messenger-message-bot-stack-border-top-left-radius Optional 8px Border radius top left for consecutive agent messages, overrides agent top left radius
df-messenger-message-bot-stack-border-top-right-radius Optional 8px Border radius top right for consecutive agent messages, overrides agent top right radius
df-messenger-message-bot-stack-border-bottom-left-radius Optional 8px Border radius bottom left for consecutive agent messages, overrides agent bottom left radius
df-messenger-message-bot-stack-border-bottom-right-radius Optional 8px Border radius bottom right for consecutive agent messages, overrides agent bottom right radius
df-messenger-message-user-stack-border-top-left-radius Optional 8px Border radius top left for consecutive user messages, overrides user top left radius
df-messenger-message-user-stack-border-top-right-radius Optional 8px Border radius top right for consecutive user messages, overrides user top right radius
df-messenger-message-user-stack-border-bottom-left-radius Optional 8px Border radius bottom left for consecutive user messages, overrides user bottom left radius
df-messenger-message-user-stack-border-bottom-right-radius Optional 8px Border radius bottom right for consecutive user messages, overrides user bottom right radius
df-messenger-message-user-writing-image-width Optional 24px Width of the image shown while the agent is writing, only active if bot-writing-image is set
df-messenger-message-bot-writing-image-height Optional 24px Height of the image shown while the agent is writing, only active if bot-writing-image is set
df-messenger-message-bot-writing-font-weight Optional normal Font weight of the text shown while the agent is writing, only active if bot-writing-text is set
df-messenger-message-bot-writing-font-size Optional 14px Text size of the text shown while the agent is writing, only active if bot-writing-text is set
df-messenger-message-bot-writing-border Optional none Border of the message shown while the agent is writing
df-messenger-message-bot-writing-background Optional #ecf3fe Background of the message shown while the agent is writing
df-messenger-message-bot-writing-padding Optional 12px Padding of the message shown while the agent is writing
df-messenger-message-bot-writing-spacing Optional 10px Space between the message shown while the agent is writing and the previous message
df-messenger-message-error-background Optional black Background of the error message shown in the agent dialog
df-messenger-message-error-font-family Optional "Google Sans", "Helvetica Neue", sans-serif Font family for the error message shown in the agent dialog
df-messenger-message-error-font-size Optional 12px Font size for the error message shown in the agent dialog
df-messenger-message-error-font-color Optional white Text color for the error message shown in the agent dialog
df-messenger-chat-scroll-button-display Optional none Defines the display of the "Jump to Bottom" button, allowed values are block or none
df-messenger-chat-scroll-button-container-padding Optional 8px Padding of the container around the "Jump to Bottom" button
df-messenger-chat-scroll-button-font-size Optional 14px Text size of the "Jump to Bottom" button
df-messenger-chat-scroll-button-font-color Optional white Text color of the "Jump to Bottom" button
df-messenger-chat-scroll-button-background Optional #0b57d0 Background of the "Jump to Bottom" button
df-messenger-chat-scroll-button-border-radius Optional 999px Border radius of the "Jump to Bottom" button
df-messenger-chat-messagelist-scroll-shadow-background Optional radial-gradient(farthest-side at 50% 100%, rgba(0,0,0,.2), transparent) bottom Shadow that is shown on the bottom of the message list when the list is not scrolled to the bottom, set to none to disable

Styling for user input

For the user input, the following CSS variables can be provided:

Properties Input policy Default value Description
df-messenger-send-icon-color Optional #0b57d0 Color of the "send" icon in the user input
df-messenger-send-icon-color-hover Optional #0b57d0 Color of the "send" icon in the user input when hovered
df-messenger-send-icon-color-active Optional #0b57d0 Color of the "send" icon in the user input when text can be sent
df-messenger-send-icon-offset-x Optional 0 Vertical offset of the "send" icon in the user input
df-messenger-send-icon-offset-y Optional -2px Horizontal offset of the "send" icon in the user input
df-messenger-input-background Optional white Background of the user input
df-messenger-input-padding Optional 8px Overall padding between the user input field (including send message button) and the container.
df-messenger-input-inner-padding Optional 5px 48px 5px 0 Inner padding between the user input field (not including send message button) and the container.
df-messenger-input-border Optional none Border of the user input
df-messenger-input-border-top Optional 1px solid #e0e0e0 Top border of the user input
df-messenger-input-border-bottom Optional none Border bottom of the text field of the user input
df-messenger-input-font-family Optional "Google Sans", "Helvetica Neue", sans-serif Font family of the user input
df-messenger-input-font-color Optional #1f1f1f Text color of the user input
df-messenger-input-font-size Optional 14px Text size of the user input
df-messenger-input-font-weight Optional normal Font weight of the user input
df-messenger-input-box-border Optional none Border of the user input box
df-messenger-input-box-focus-border Optional none Border of the user input box while focused
df-messenger-input-box-border-radius Optional 0 Border radius of the user input box
df-messenger-input-box-padding Optional 8px 0 Padding of the user input box
df-messenger-input-box-focus-padding Optional 8px 0 Padding of the user input box while focused
df-messenger-input-gutter Optional stable Scrollbar gutter of the user input

Styling for authentication overlay

When using an authenticated setup, the following CSS variables can be provided for the overlay:

Properties Input policy Default value Description
df-messenger-auth-background Optional rgba(204, 204, 204, .8) Background of the agent dialog box when authentication is shown
df-messenger-auth-button-background Optional #0b57d0 Background of the authentication button
df-messenger-auth-button-font-family Optional "Google Sans", "Helvetica Neue", sans-serif Font family of the authentication button
df-messenger-auth-button-font-color Optional white Text color of the authentication button
df-messenger-auth-button-font-size Optional 14px Text size of the authentication button
df-messenger-auth-button-border Optional none Border of the authentication button
df-messenger-auth-button-border-radius Optional 8px Border radius of the authentication button

Feedback styling

When the answer feedback feature is enabled, the following CSS variables can be provided for the feedback controls.

Properties Input policy Default value Description
df-messenger-message-feedback-icon-distance Optional 8px Distance between the thumbs up and down buttons
df-messenger-message-feedback-icon-font-color Optional #444746 Color of the thumbs up and down buttons
df-messenger-message-feedback-icon-font-color-active Optional #444746 Color of the thumbs up and down buttons when active
df-messenger-message-feedback-icon-border Optional none Border of the thumbs up and down buttons
df-messenger-message-feedback-icon-border-radius Optional 0 Border radius of the thumbs up and down buttons
df-messenger-message-feedback-icon-background Optional none Background of the thumbs up and down buttons
df-messenger-message-feedback-icon-background-hover Optional none Background of the thumbs up and down buttons when hovered
df-messenger-message-feedback-icon-padding Optional 0 Padding of the thumbs up and down buttons
df-messenger-message-rich-feedback-spacing Optional 10px Spacing of elements in the rich feedback
df-messenger-message-rich-feedback-padding Optional 0 Padding of the rich feedback
df-messenger-message-rich-feedback-background Optional none Background of the rich feedback
df-messenger-message-rich-feedback-border-radius Optional 0 Border radius of the rich feedback
df-messenger-message-rich-feedback-border Optional none Border of the rich feedback
df-messenger-rich-feedback-offset-left Optional 0 Offset on the left side

JavaScript events

Dialogflow Messenger triggers a variety of events that you can create event listeners for. Some events have a detail object field, which provides more information about the event.

The following events are supported:

Event Trigger Detail Fields
df-messenger-loaded The agent dialog is first loaded. none.
df-accordion-clicked User clicked the accordion. none.
df-button-clicked User clicked a button. actionLink: anchor href of the clicked button, if specified.

event: event of the clicked button, if specified.
df-chip-clicked User clicked a chip. actionLink: anchor href of the clicked chip, if specified.

text: text of the clicked chip.
df-citation-clicked User clicked a citation. actionLink: anchor href of the citation.
df-info-card-clicked User clicked a info-card. actionLink: anchor href of the info-card.
df-list-element-clicked User clicked a list element. event: event of the clicked list element, if specified.
df-messenger-error A request to the backend fails. error: error that occurred.
df-request-sent A request sent to the backend. requestBody: request that was sent.
df-response-received A response has arrived to the agent dialog. messages: list of parsed response messages.

raw: verbatim response that was received.
df-session-expired The session with the agent expired. none.
df-session-ended The session has ended. none.
df-url-suggested URLs of suggested resources. suggestedUrls: list of suggested URLs.
df-user-input-entered The user entered text. input: value the user entered.
df-chat-open-changed The chat is opened or closed.

Only active if the df-messenger-chat-bubble is used.
isOpen: new state of the chat

Event handling example:

document.addEventListener('df-user-input-entered', (event) => {
  // Extract the user input.
  const userInput = event.detail.input;
});
document.addEventListener('df-url-suggested', (event) => {
  // Extract the URLs suggested by the agent.
  const agentSuggestedUrls = event.detail.suggestedUrls;
});

Customization example

The following example shows HTML customization, CSS customization, and event handling:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
  <meta http-equiv="Pragma" content="no-cache" />
  <meta http-equiv="Expires" content="0" />
  <title>My chat</title>
  <style>
    df-messenger {
      /*
       * Customize as required. df-messenger will fill the
       * space that is provided.
      */
      position: absolute;
      right: 0;
      top: 0;
      bottom: 0;
      width: 320px;
    }
  </style>
  <script src="https://www.gstatic.com/dialogflow-console/fast/df-messenger/prod/v1/df-messenger.js"></script>
</head>
<body>
<df-messenger
    location="global" <!-- TODO: update agent location as needed -->
    project-id="my-project-id" <!-- TODO: update project ID -->
    agent-id="my-agent-id" <!-- TODO: update agent ID -->
    language-code="en" <!-- TODO: update agent language as needed -->
>
  <df-messenger-chat
      chat-title="Agent Name" <!-- TODO: update dialog title as needed -->
  ></df-messenger-chat>
</df-messenger>

<script>
  // An example of handling events: Navigate to the first suggested URL.
  document.addEventListener('df-url-suggested', (event) => {
    if (Array.isArray(event.detail.suggestedUrls) &&
      event.detail.suggestedUrls.length) {
      window.location.href = event.detail.suggestedUrls[0];
  }
});
</script>
</body>
</html>

JavaScript functions

Dialogflow Messenger provides functions you can call to affect its behavior.

renderCustomText

This function renders a simple text message, as if it came from the agent as simple text response or it was entered by the end-user.

Arguments:

  • string: text message
  • boolean: true for a message from agent, false from end-user

Return:

  • void

For example:

const dfMessenger = document.querySelector('df-messenger');
dfMessenger.renderCustomText('Custom text', true);

renderCustomCard

This function renders a custom card, as if it came from Dialogflow fulfillment.

Arguments:

  • payload: a list of custom payload responses, which are defined in the Fulfillment section.

Return:

  • void

For example:

const dfMessenger = document.querySelector('df-messenger');
const payload = [
  {
    "type": "info",
    "title": "Info item title",
    "subtitle": "Info item subtitle",
    "image": {
      "rawUrl": "https://example.com/images/logo.png"
    },
    "anchor": {
      "href": "https://example.com",
      "target": "_blank"
    }
  }
];
dfMessenger.renderCustomCard(payload);

sendQuery

This function sends a query to the Dialogflow API and waits for the response. This effectively simulates an end-user input that is normally provided to the agent dialog. The response will be handled as any end-user's query would.

Arguments:

  • string: text query

Return:

  • Promise<void>: return value for the asynchronous operation

For example:

const dfMessenger = document.querySelector('df-messenger');
dfMessenger.sendQuery('Describe shipping costs.');

sendRequest

This function sends a request to the Dialogflow API and waits for the response.

Arguments:

  • string: request type, supports query (see also sendQuery above) and event (see custom event)
  • any: payload that corresponds to the request type, which is currently a string for both supported request types

Return:

  • Promise<void>: return value for the asynchronous operation

For example:

const dfMessenger = document.querySelector('df-messenger');
dfMessenger.sendRequest('query', 'Describe shipping costs.');

setQueryParameters

This function sets default values for the queryParams field of the Dialogflow API detectIntent request. Other Dialogflow Messenger methods may replace respective default values in the query parameters.

Arguments:

Return:

  • void

For example:

const dfMessenger = document.querySelector('df-messenger');
const queryParameters = {
  timeZone: "America/New_York"
};
dfMessenger.setQueryParameters(queryParameters);

setContext

This function sends generative personalization information about to the end-user to Dialogflow. This information will persist for the remainder of the session.

Arguments:

  • object: JSON data, see generative personalization documentation

Return:

  • void

For example:

const dfMessenger = document.querySelector('df-messenger');
const metadata = {
  "subscription plan": "Business Premium Plus",
  "devices owned": [
    {
      model: "Google Pixel 7",
    },
    {
      model: "Google Pixel Tablet",
    },
  ],
};
dfMessenger.setContext(metadata);

clearStorage

This function clears the persistent storage of the agent dialog. It also clears the current state of the agent dialog.

Arguments:

  • none

Return:

  • void

For example:

const dfMessenger = document.querySelector('df-messenger');
dfMessenger.clearStorage();

clearAuthentication

This function clears the authentication of the agent dialog.

Arguments:

  • none

Return:

  • void

For example:

const dfMessenger = document.querySelector('df-messenger');
dfMessenger.clearAuthentication();

startNewSession

This function starts a new session inside the agent dialog. It can either keep or reset the current message history. It does not clear the users authentication.

Arguments:

Name Type Description
args object? Optional argument to configure the new session creation.
args.retainHistory boolean? Optional flag to retain history. If set to true the history will be kept, otherwise it will be erased.

Return:

  • void

For example:

const dfMessenger = document.querySelector('df-messenger');
dfMessenger.startNewSession({ retainHistory: true });

openChat

This function opens the chat. Call it on the df-messenger-chat-bubble element to open the chat. Does nothing if the chat is already open.

Arguments:

  • none

Return:

  • void

For example

const dfMessengerBubble = document.querySelector('df-messenger-chat-bubble');
dfMessengerBubble.openChat();

closeChat

This function closes the chat. Call it on the df-messenger-chat-bubble element to close the chat. Does nothing if the chat is already closed.

Arguments:

  • none

Return:

  • void

For example

const dfMessengerBubble = document.querySelector('df-messenger-chat-bubble');
dfMessengerBubble.closeChat();

Fulfillment

When creating a custom card fulfillment, you can create Text Responses and Custom Payloads. The text responses are used for plain text and markdown agent responses, and the custom payloads are used for rich responses. The custom payload format for all response types has the following basic structure:

{
  "richContent": [
    [
      {
        "type": "type-id",
        ...
      },
      {
        "type": "type-id",
        ...
      }
    ],
    [
      {
        "type": "type-id",
        ...
      },
      {
        "type": "type-id",
        ...
      }
    ]
  ]
}

Note that the richContent value allows one outer and multiple inner arrays. Responses within an inner array are bound together in a single visual card. When the outer array contains multiple inner arrays, multiple cards are shown—one for each inner array.

The remaining subsections describe the various types of responses you can configure for a custom payload.

Text response

Dialogflow Messenger text screenshot

The text response supports plain text and Markdown.

Info response type

Dialogflow Messenger info type screenshot

The info response type is a simple title card that users can click or touch.

The following table describes the fields:

Name Type Description
type string Response type: "info"
title string Card title
subtitle string Card subtitle
image object Image
image.rawUrl string Public URL for image
anchor object Anchor to follow when element is clicked
anchor.href string URL of the anchor
anchor.target string Target of the anchor, defaults to _blank

For example:

{
  "richContent": [
    [
      {
        "type": "info",
        "title": "Info item title",
        "subtitle": "Info item subtitle",
        "image": {
          "rawUrl": "https://example.com/images/logo.png"
        },
        "anchor": {
          "href": "https://example.com"
        }
      }
    ]
  ]
}

Description response type

Dialogflow Messenger description type screenshot

The description response type is an informative card that can have multiple lines of text.

The following table describes the fields:

Name Type Description
type string Response type: "description"
title string Card title
text array<string> Array of strings, where each string is rendered on a new line

For example:

{
  "richContent": [
    [
      {
        "type": "description",
        "title": "Description title",
        "text": [
          "This is text line 1.",
          "This is text line 2."
        ]
      }
    ]
  ]
}

Image response type

Dialogflow Messenger image type screenshot

The image response type is an image card that users can click or touch.

The following table describes the fields:

Name Type Description
type string Response type: "image"
rawUrl string Public URL for image
accessibilityText string Alt text for image

For example:

{
  "richContent": [
    [
      {
        "type": "image",
        "rawUrl": "https://example.com/images/logo.png",
        "accessibilityText": "Example logo"
      }
    ]
  ]
}

The following CSS variables can be provided:

Properties Input policy Default value Description
df-messenger-image-border-radius Optional 8px Border radius of the image

Video response type

Dialogflow Messenger video type screenshot

The video response type renders a video element that can either be a direct video from URL, played directly in the messenger, or a link to a video.

Name Type Description
type string Response type: "video"
title string Optional video title
source object The video's source
source.type string A type of video source, either link or raw
source.anchor object Anchor to follow when element is clicked
source.embeddedPlayer string A link type video may be embedded rather than link to the player's web page. This is only implemented for a known set of players, supports youtube.
source.thumbnail object Thumbnail to show for the anchor
source.thumbnail.rawUrl string The URL of the thumbnail
source.rawUrl string URL for a raw type video

For example:

{
  "richContent": [
    [
      {
        "type": "video",
        "source": {
          "type": "link",
          "anchor": {
            "href": "https://www.youtube.com/watch?v=cNfINi5CNbY"
          }
        }
      }
    ]
  ]
}

The following CSS variables can be provided:

Properties Input policy Default value Description
df-messenger-video-width Optional auto Width of a video (limited by max-width\: 100%)
df-messenger-video-height Optional auto Height of a video
df-messenger-video-embed-width Optional 560px Width of an embedded video (limited by max-width\: 100%)
df-messenger-video-embed-height Optional 315px Height of an embedded video
df-messenger-video-border Optional 1px solid #e0e0e0 Border of the video
df-messenger-video-border-radius Optional 8px Border radius of the video

Button response type

Dialogflow Messenger button type screenshot

The button response type is a small button with an icon that users can click or touch.

The following table describes the fields:

Name Type Description
type string Response type: "button"
icon object Icon for button
icon.type string Icon from the Material icon library. The default icon is an arrow
icon.color string Color hexcode
image object Image for the button, takes priority over icon
image.rawUrl string Public URL for image
mode string Optional, if set to "blocking", user input is disabled until the user clicks the button
text string Button text
anchor object Anchor to follow when element is clicked
anchor.href string URL of the anchor
anchor.target string Target of the anchor, defaults to _blank
event object Dialogflow event that is triggered when the button is clicked.

For example:

{
  "richContent": [
    [
      {
        "type": "button",
        "icon": {
          "type": "chevron_right",
          "color": "#FF9800"
        },
        "mode": "blocking",
        "text": "Button text",
        "anchor": {
          "href": "https://example.com"
        },
        "event": {
          "event": ""
        }
      }
    ]
  ]
}

The following CSS variables can be provided:

Properties Input policy Default value Description
df-messenger-button-border Optional none Border of a button
df-messenger-button-border-radius Optional 8px Border radius of a button
df-messenger-button-font-color Optional #1f1f1f Text color of a button
df-messenger-button-font-family Optional "Google Sans", "Helvetica Neue", sans-serif Font family of a button
df-messenger-button-font-size Optional 14px Font size of a button
df-messenger-button-padding Optional 12px Padding of a button
df-messenger-button-icon-spacing Optional 12px Space between button icon and text
df-messenger-button-icon-font-size Optional 24px Size of the button icon
df-messenger-button-image-size Optional 24px Size of the button image
df-messenger-button-image-offset Optional 0 Offset of the button image, allows negative values to offset padding

List response type

Dialogflow Messenger list type screenshot

The list response type is a card with multiple options users can select from.

The response contains an array of list and divider response types. The following table describes the list type:

Name Type Description
type string Response type: "list"
title string Option title
subtitle string Option subtitle
event object Dialogflow event that is triggered when the option is clicked
anchor object Anchor to follow when element is clicked
anchor.href string URL of the anchor
anchor.target string Target of the anchor, defaults to _blank
image object Image
image.rawUrl string Public URL for image

The following table describes the divider type:

Name Type Description
type string Response type: "divider"

For example:

{
  "richContent": [
    [
      {
        "type": "list",
        "title": "List item 1 title",
        "subtitle": "List item 1 subtitle",
        "event": {
          "event": ""
        }
      },
      {
        "type": "list",
        "title": "List item 2 title",
        "subtitle": "List item 2 subtitle",
        "event": {
          "event": ""
        }
      }
    ]
  ]
}

Accordion response type

Dialogflow Messenger accordion type screenshot

The accordion response type is a small card that a user can click or touch to expand and reveal more text.

The following table describes the fields:

Name Type Description
type string Response type: "accordion"
title string Accordion title
subtitle string Accordion subtitle
image object Image
image.rawUrl string Public URL for image
text string Accordion text

For example:

{
  "richContent": [
    [
      {
        "type": "accordion",
        "title": "Accordion title",
        "subtitle": "Accordion subtitle",
        "image": {
          "rawUrl": "https://example.com/images/logo.png"
        },
        "text": "Accordion text"
      }
    ]
  ]
}

Suggestion chip response type

Dialogflow Messenger chips type screenshot

The suggestion chip response type provides the end-user with a list of clickable suggestion chips.

The following table describes the fields:

Name Type Description
type string Response type: "chips"
options array<object> Array of Option objects
options[].mode string Optional, if set to "blocking", user input is disabled until the user clicks the chip
options[].text string Option text
options[].image object Optional, option Image
options[].image.rawUrl string Option public URL for image
options[].anchor object Optional, Anchor to follow when element is clicked
options[].anchor.href string URL of the anchor
options[].anchor.target string Target of the anchor, defaults to _blank

For example:

{
  "richContent": [
    [
      {
        "type": "chips",
        "options": [
          {
            "mode": "blocking",
            "text": "Chip 1",
            "image": {
              "rawUrl": "https://example.com/images/logo.png"
            },
            "anchor": {
              "href": "https://example.com"
            }
          },
          {
            "text": "Chip 2",
            "image": {
              "rawUrl": "https://example.com/images/logo.png"
            },
            "anchor": {
              "href": "https://example.com"
            }
          }
        ]
      }
    ]
  ]
}

The following CSS variables can be provided:

Properties Input policy Default value Description
df-messenger-chips-spacing Optional 10px Space above the chips to the preceding message
df-messenger-chips-border-color Optional #e0e0e0 Border color of a chip
df-messenger-chips-border-color-hover Optional #e0e0e0 Border color of a chip when hovered
df-messenger-chips-border-radius Optional 999px Border radius of a chip
df-messenger-chips-background Optional white Background of a chip
df-messenger-chips-background-hover Optional rgba(68, 71, 70, 0.08) Background of a chip when hovered
df-messenger-chips-padding Optional 6px 16px Padding of a chip
df-messenger-chips-font-color Optional black Text color of a chip
df-messenger-chips-font-family Optional "Google Sans", "Helvetica Neue", sans-serif Font family of a chip
df-messenger-chips-font-size Optional 14px Text size of a chip
df-messenger-chips-font-weight Optional normal Font weight of a chip
df-messenger-chips-font-weight-hover Optional normal Font weight of a chip when hovered
df-messenger-chips-box-shadow Optional 0 2px 2px 0 rgba(0, 0, 0, 0.24) Box shadow of a chip

Citations response type

Dialogflow Messenger citations type screenshot

The citations response type provides the end-user with a list of clickable citation links.

The following table describes the fields:

Name Type Description
type string Response type: "match_citations"
citations array<object> Array of Citation objects
citations[].title string Citation title
citations[].subtitle string Citation subtitle (currently ignored)
citations[].anchor object Anchor to follow when element is clicked
citations[].anchor.href string URL of the anchor
citations[].anchor.target string Target of the anchor, defaults to _blank

For example:

{
  "richContent": [
    [
      {
        "type": "match_citations",
        "citations": [
          {
            "title": "Source 1",
            "subtitle": "",
            "anchor": {
              "href": "https://example.com/1"
            }
          },
          {
            "title": "Source 2",
            "subtitle": "",
            "anchor": {
              "href": "https://example.com/2"
            }
          }
        ]
      }
    ]
  ]
}

The following CSS variables can be provided:

Properties Input policy Default value Description
df-messenger-citations-spacing Optional 10px Space above the citations to the preceding message
df-messenger-citations-message-display Optional block Defines display of the note above citations, allowed values are block or none
df-messenger-citations-message-font-color Optional #041e49 Text color of the note above citations
df-messenger-citations-message-font-size Optional 12px Text size of the note above citations
df-messenger-citations-flex-direction Optional row Flex direction property of the citations, recommended to use row (horizontal with line breaks) or column (vertical)
df-messenger-citations-border-color Optional #1a73e8 Border color of a citation
df-messeenger-citations-border-color-hover Optional #1a73e8 Border color of a citation when hovered
df-messenger-citations-border-radius Optional 4px Border radius of a citation
df-messenger-citations-padding Optional 8px Padding of a citation
df-messenger-citations-background Optional white Background of a citation
df-messenger-citations-background-hover Optional rgba(68, 71, 70, 0.08) Background of a citation when hovered
df-messenger-citations-font-color Optional #1a73e8 Text color of a citation
df-messenger-citations-font-family Optional "Google Sans", "Helvetica Neue", sans-serif Font family of a citation
df-messenger-citations-font-size Optional 11px Text size of a citation
df-messenger-citations-icon-font-size Optional 14px Text size of the icon of a citation
df-messenger-citations-font-weight Optional normal Font weight of a citation
df-messenger-citations-font-weight-hover Optional normal Font weight of a citation when hovered
df-messenger-citations-icon-spacing Optional 4px Space between icon and text in a citation
df-messenger-citations-box-shadow Optional none Box shadow of a citation

HTML response type

Dialogflow Messenger html type screenshot

The HTML response type provides the end-user with a HTML message.

The following table describes the fields:

Name Type Description
type string Response type: "html"
html string Text content of the message, supports HTML

Supported HTML tags:

  • a - Anchor element (used for creating hyperlinks)
  • b - Bold element (used for bolding text)
  • i - Italic element (used for italicizing text)
  • u - Underline element (used for underlining text)
  • h1 - Heading 1 element (used for the main heading of a page)
  • h2 - Heading 2 element (used for subheadings)
  • h3 - Heading 3 element (used for sub-subheadings)
  • p - Paragraph element (used for creating paragraphs of text)
  • br - Line break element (used for creating line breaks within a paragraph)
  • table - Table element (used for creating tables)
  • tr - Table row element (used for creating rows within a table)
  • thead - Table header element (used for creating a header within a table)
  • th - Table header data/cell element (used for creating cells within a table header row)
  • tbody - Table body element (used for creating a body within a table)
  • td - Table data/cell element (used for creating cells within a table row)
  • ul - Unordered list element (used for creating bulleted lists)
  • ol - Ordered list element (used for creating numbered lists)
  • li - List item element (used for creating items within a list)
  • img - Image element (used for showing an image, see also url-allowlist above)
  • div - Container element
  • span - Inline container element

For example:

{
  "richContent": [
    [
      {
        "type": "html",
        "html": "<b>Bold text</b> <i>Italic text</i> <u>Underlined text</u>"
      }
    ]
  ]
}

Styling HTML and Markdown

For anchor elements (HTML a element and Markdown link), the following CSS variables can be provided:

Properties Input policy Default value Description
df-messenger-link-decoration Optional underline Decoration of a link element
df-messenger-link-font-color Optional #0b57d0 Font color of an unvisited link element
df-messenger-link-visited-font-color Optional #0b57d0 Font color of a visited link element
df-messenger-link-hover-font-color Optional #0b57d0 Font color when hovering a link element
df-messenger-link-background Optional transparent Background of a link element
df-messenger-link-padding Optional 0 Padding of a link element
df-messenger-link-border Optional none Border of a link element
df-messenger-link-border-radius Optional 0 Border radius of a link element

For table elements (HTML table element and Markdown tables), the following CSS variables can be provided:

Properties Input policy Default value Description
df-messenger-table-font-size Optional 14px Text size in a table element
df-messenger-table-font-color Optional #1f1f1f Text color in a table element
df-messenger-table-align Optional left Alignment of text in a table cell
df-messenger-table-padding Optional 0 Padding in a table cell
df-messenger-table-border-collapse Optional separate Border collapse mode of a table, use separate to enable border-radius
df-messenger-table-border-radius Optional 0 Border radius of a table
df-messenger-table-header-border-radius Optional 0 Border radius of the table header
df-messenger-table-border-top Optional none Border top of a table row
df-messenger-table-border-top-first Optional none Border top of the first table row
df-messenger-table-border-bottom Optional none Border bottom of a table row
df-messenger-table-border-bottom-last Optional none Border bottom of the last table row
df-messenger-table-border-left Optional none Border left of a table cell
df-messenger-table-border-left-first Optional none Border left of the first table cell in a row
df-messenger-table-border-right Optional none Border right of a table cell
df-messenger-table-border-right-last Optional none Border right of the last table cell in a row
df-messenger-table-background Optional transparent Background of a table row
df-messenger-table-even-background Optional transparent Background of even numbered table rows
df-messenger-table-odd-background Optional transparent Background of odd numbered table rows
df-messenger-table-header-font-size Optional 14px Text size in a table header element
df-messenger-table-header-font-weight Optional bold Font weight in a table header element
df-messenger-table-header-font-color Optional #1f1f1f Text color in a table header element
df-messenger-table-header-align Optional left Alignment of text in a table header cell
df-messenger-table-header-padding Optional 0 Padding in a table header cell
df-messenger-table-header-border-top Optional none Border top of the table header row
df-messenger-table-header-border-bottom Optional none Border bottom of the table header row
df-messenger-table-header-border-left Optional none Border left of a cell in the table header row
df-messenger-table-header-border-left-first Optional none Border left of the first cell in the table header row
df-messenger-table-header-border-right Optional none Border right of a cell in the table header row
df-messenger-table-header-border-right-last Optional none Border right of the last cell in a table header row
df-messenger-table-header-background Optional transparent Background of the table header row

Custom Template response type

Dialogflow Messenger custom template type screenshot

The custom template response type renders a custom element defined on the customer's website. The element is not placed inside a card and always stands on its own.

The following table describes the fields:

Name Type Description
type string Response type: "custom_template"
name string Name of the custom element
payload Object Payload to pass to the custom element

For example:

{
  "richContent": [
    [
      {
        "type": "custom_template",
        "name": "custom-element-example",
        "payload": {
          "text": "Hello World"
        }
      }
    ]
  ]
}

On your website, the custom element needs to be registered under the exact name from the name field of the response. The payload field is passed to the custom element as dfPayload after construction (but before connectedCallback). The field may contain arbitrary JSON. In addition, dfResponseId is passed to the element.

Using the response from the example, here is an example implementation of a custom element:

class CustomElementExample extends HTMLElement {
  constructor() {
    super();
    // The `dfPayload` field will be provided before `connectedCallback` is
    // being called.
    this.dfPayload = null;
    // The `dfResponseId` field will be provided before `connectedCallback` is
    // being called.
    this.dfResponseId = null;
    // It is not strictly required but recommended to contain the custom
    // element in a shadow root.
    // https://developer.mozilla.org/en-US/docs/Web/API/ShadowRoot
    this.renderRoot = this.attachShadow({mode: 'open'});
  }

  /** Web component Lifecycle method. */
  connectedCallback() {
    const div = document.createElement('div');

    // The `.text` must match the payload's structure in `richContent.payload`.
    div.innerText = this.dfPayload.text;

    this.renderRoot.appendChild(div);
  }
}

(function() {
  // Registers the element. This name must match the name in
  // `richContent.payload`.
  customElements.define('custom-element-example', CustomElementExample);
})();

Combining response types

Dialogflow Messenger custom card screenshot

The individual rich message elements for Dialogflow Messenger can be used to construct a custom card to fit your needs.

Here's an example using some of the elements listed in the fulfillment section:

{
  "richContent": [
    [
      {
        "type": "image",
        "rawUrl": "https://example.com/images/logo.png",
        "accessibilityText": "Dialogflow across platforms"
      },
      {
        "type": "info",
        "title": "Dialogflow",
        "subtitle": "Build natural and rich conversational experiences",
        "anchor": {
          "href": "https://cloud.google.com/dialogflow/docs"
        }
      },
      {
        "type": "chips",
        "options": [
          {
            "text": "Case Studies",
            "anchor": {
              "href": "https://cloud.google.com/dialogflow/case-studies"
            }
          },
          {
            "text": "Docs",
            "anchor": {
              "href": "https://cloud.google.com/dialogflow/docs"
            }
          }
        ]
      }
    ]
  ]
}

The following CSS variables can be provided:

Properties Input policy Default value Description
df-messenger-card-background Optional white Background of a custom card
df-messenger-card-padding Optional 16px Padding of elements in a custom card
df-messenger-card-border Optional 1px solid #e0e0e0 Border of a custom card
df-messenger-card-border-radius Optional 8px Border radius of a custom card
df-messenger-card-border-top-left-radius Optional 8px Border radius top left of a custom card
df-messenger-card-border-top-right-radius Optional 8px Border radius top right of a custom card
df-messenger-card-border-bottom-left-radius Optional 8px Border radius bottom left of a custom card
df-messenger-card-border-bottom-right-radius Optional 8px Border radius bottom right of a card
df-messenger-card-stack-border-top-left-radius Optional 8px Border radius top left for consecutive custom cards overrides top left radius
df-messenger-card-stack-border-top-right-radius Optional 8px Border radius top right for consecutive custom cards overrides top right radius
df-messenger-card-stack-border-bottom-left-radius Optional 8px Border radius bottom left for consecutive custom cards overrides bottom left radius
df-messenger-card-stack-border-bottom-right-radius Optional 8px Border radius bottom right for consecutive custom cards overrides bottom right radius
df-messenger-card-box-shadow Optional 0 2px 2px 0 rgba(0, 0, 0, 0.24) Box shadow of a custom card

Answer Feedback

If answer feedback is enabled, by default the chat dialog will add thumbs up and thumbs down buttons to the user interface. During the conversation, an end-user can click these buttons to provide feedback on the agent responses. If the user selects thumbs down, they can optionally provide a reason for the negative feedback.

Custom Feedback component

To specify a custom feedback element, a new custom element has to be defined on the website. To submit the feedback, the element must emit a df-custom-submit-feedback-clicked event. The contained detail field must be a string.

class CustomFeedbackElement extends HTMLElement {
  constructor() {
    super();
    // It is not strictly required but recommended to contain the custom
    // element in a shadow root.
    this.renderRoot = this.attachShadow({mode: 'open'});
  }

  // Web component Lifecycle method.
  connectedCallback() {
    const wrapper = document.createElement('div');

    // Build the component as required.
    const button = document.createElement('button');
    button.innerText = 'Submit';
    button.addEventListener('click', () => {
      this._onSubmitClick();
    });
    wrapper.appendChild(button);

    this.renderRoot.appendChild(wrapper);
  }

  // Called when Submit button is clicked.
  _onSubmitClick() {
    const event = new CustomEvent("df-custom-submit-feedback-clicked", {
      // `detail` may be any string,
      // this will be sent to the backend to be stored.
      detail: JSON.stringify({
        "usefulness": 2,
        "accuracy": 3,
      }),
      // Required to propagate up the DOM tree
      // https://developer.mozilla.org/en-US/docs/Web/API/Event/bubbles
      bubbles: true,
      // Required to propagate across ShadowDOM
      // https://developer.mozilla.org/en-US/docs/Web/API/Event/composed
      composed: true,
   });
   this.dispatchEvent(event);
  }
}

(function() {
  // Registers the element. This name must be "df-external-custom-feedback".
  customElements.define('df-external-custom-feedback', CustomFeedbackElement);
})();

Debugging

To test your agent with Dialogflow Messenger locally:

  • Embed the Dialogflow Messenger element in a page as described above.
  • Start a local HTTP server for that page with a specific port.
  • Access that page at http://localhost:port_number.