Passing context variables to Live Agent and Virtual Agent chat

  • Release version: Yokohama
  • Updated January 30, 2025
  • 2 minutes to read
  • Summarize
    Summarized using AI
    This content was generated using new OpenAI-powered functionality. Results are provided on an as is basis and are not guaranteed to be accurate or complete.

    Summary of Passing context variables to Live Agent and Virtual Agent chat

    This guide explains how ServiceNow customers can pass chat context variables and customize chat behavior when starting Live Agent or Virtual Agent chat sessions using the NowChatService API. By leveraging thecontextDataparameter and optionalNowChatConfiguration, customers can tailor chat interactions and UI elements to improve user experience and operational control.

    Show full answer Show less

    Key Features

    • Passing Context Variables: Use the startChat(contextData:completion:) function to provide context data as a dictionary. This supports passing key-value pairs that can influence chat routing, display, or processing.
    • Chat Configuration Options: Customize chat behavior by supplying a NowChatConfiguration object when initiating chat, which includes:
      • closePrompt: Configure the text and buttons for the prompt displayed when a user attempts to exit a chat window. Includes parameters such as header, message, acceptButtonTitle, and declineButtonTitle.
      • disabledFeatures: Disable specific NowChat features to control user options during chat (e.g., disabling starting a new conversation).
      • conversationOptions: Apply conversation behaviors such as forcing new conversations or ending conversations upon exit.
      • uiConfiguration: Customize UI components like close button appearance and attachment upload button visibility.
    • UI Customization: The example demonstrates how to create custom close button types (text or image) and configure attachment upload button visibility.
    • Chat Service Lifecycle: Shows initializing the chat service with NowChat.makeChatService, creating the chat UI with configured options, and starting the chat session with error handling.

    Practical Application for ServiceNow Customers

    ServiceNow customers can enhance their chat integrations by passing relevant context variables that influence routing or agent handling directly when the chat starts. Additionally, they gain control over the chat interface and user options through NowChatConfiguration, enabling a consistent and branded chat experience that aligns with business requirements.

    By following the implementation patterns and API usage described, customers can:

    • Seamlessly integrate contextual information into chat sessions to improve agent efficiency and customer satisfaction.
    • Customize chat UI prompts and controls to guide user interactions and prevent accidental chat closures.
    • Control available chat features and conversation flow behaviors to match organizational policies or service delivery models.
    • Handle chat service initialization and lifecycle events robustly, including error handling and UI state management.

    You can pass chat context variables when starting a chat session by passing the contextData parameter.

    You can pass this value using the NowChatService - startChat(contextData: [String: Any]? = nil, _ completion: @escaping (Result<Void, NowChatServiceError>) -> Void) functions.

    For additional information on chat context variables, see Live agent chat context variables.

    In addition, you can also pass an optional NowChatConfiguration parameter when starting a chat session to modify some of the behavior of NowChat.

    • closePrompt: Prompt text that appears before exiting a chat window. You define this prompt text through the following parameters:
      • header: Nullable string value that appears on the prompt’s header.
      • message: String value that appears on the prompt’s main body.
      • acceptButtonTitle: String value that appears on the primary button of the prompt. This button closes the chat window.
      • declineButtonTitle: String value that appears on the secondary button of the prompt. This button dismisses the prompt without closing the chat window.
    • disabledFeatures: List of NowChat features to disable. Refer to the NowChatConfiguration.Feature enum class for the list of features that you can disable.
    • conversationOptions: List of conversation options to apply to NowChat. Refer to the NowChatConvestation.ConversationOption enum class for the list of options that you can apply.
    • uiConfiguration: UIConfiguration value used to configure UI components in NowChat.
    The following code example shows how to call this method:
    // Close Button Type
    func closeButtonText(title: String?) -> NowChatConfiguration.CloseButtonType? {
      guard let title else { return nil }
      return .text(title)
    }  
      
    func closeButtonImage(name imageName: String?) -> NowChatConfiguration.CloseButtonType? {
      guard let imageName,
      let buttonImage = UIImage(named: imageName) else { return nil }
      return .image(buttonImage)	
    }
    
    
    // Create the chat UI
    func makeChatScreen() -> UIViewController? {
      guard let chatService = chatService else { return nil }
      let closePrompt = NowChatConfiguration.ClosePrompt(header: "Close Window",
        message: "Are you sure you want to close the chat window?",
        acceptButtonTitle: "Yes",
        declineButtonTitle: "No")     
    
      let attachmentUploadButton = NowChatConfiguration.AttachmentUploadButton(isVisible: false) // default isVisible = true         
    
      let chatConfiguration = NowChatConfiguration(closePrompt: closePrompt,
        disabledFeatures: [.startNewConversation],
        conversationOptions: [.forceNewConversation, .endConversationOnExit],
        uiConfiguration: NowChatConfiguration.UIConfiguration(closeButton: closeButtonImage(name: "arrow.left"), attachmentUploadButton: attachmentUploadButton))
    
      let result = chatService.makeChatUI(theme: CarrascoChatTheme(chatColors: ChatColors()), chatConfiguration: chatConfiguration)
             
      switch result {
        case .success(let chatViewController): 
          return chatViewController
        case .failure(let error):
          debugPrint("Chat screen creation failed with error: \(error)")
          return nil
      }
    } 
    
    // Start the chat session
    func startChat() {
      guard let chatService = chatService else {
        debugPrint("Chat service is invalid")
        viewState = makeViewState()
        return
      } 
      chatService.startChat { [weak self] result in
        if case .failure(let error) = result {
          debugPrint("Chat session initialization failed with error: \(error)")
          self?.resetChat()
        }
      }
     }
    
    // Initialize the chat service
    private func initializeChatService() {
      NowChat.makeChatService(instanceUrl: instanceUrl, delegate: self) { [weak self] result in
        guard let self = self else { return }
        switch result {
          case .success(let service):
            self.chatService = service
          case .failure(let error):
            debugPrint("Creating the chat service failed with error: \(error)") 
        } 
        self.viewState = self.makeViewState()
      }
    }