You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在MS Bot Framework DirectLine聊天窗口中永久清除Sendbox输入框内容?

解决DirectLine Web Chat输入框无法永久清除的问题

你碰到的这个问题其实很典型——直接修改DOM输入框的value只是“表面功夫”,因为DirectLine的Web Chat组件是受控组件,输入框的实际内容是由内部的Redux状态管理的。你改了DOM但没更新状态,所以焦点一回来,组件就会从状态里把旧值又渲染回去了。

下面是两种可靠的解决方法,都是通过Web Chat官方提供的方式来更新内部状态,确保输入框内容被永久清除:

方法一:直接通过Store Dispatch Action清除

首先,在初始化Web Chat的时候,一定要保留对store的引用(这是关键):

// 创建Web Chat的store,保存引用以便后续使用
const webChatStore = window.WebChat.createStore({}, ({ dispatch }) => next => action => {
  // 这里可以添加自定义中间件,暂时不需要的话直接返回next(action)即可
  return next(action);
});

// 渲染Web Chat组件
window.WebChat.renderWebChat({
  directLine: window.WebChat.createDirectLine({ token: '你的DirectLine令牌' }),
  store: webChatStore
}, document.getElementById('webchat'));

之后,当你需要清除输入框时,调用下面的函数即可:

// 获取Web Chat的Action类型常量
const webChatActions = window.WebChat.createActionTypes();

function clearSendbox() {
  webChatStore.dispatch({
    type: webChatActions.SEND_BOX_SET_SEND_BOX,
    payload: { text: '' }
  });
}

比如你想在点击某个按钮时清除,就给按钮绑定这个函数:document.getElementById('clearBtn').addEventListener('click', clearSendbox);

方法二:消息发送成功后自动清除

如果你的需求是用户发送消息后自动清空输入框,可以在store的中间件里监听消息发送成功的事件,自动触发清除操作:

const webChatStore = window.WebChat.createStore({}, ({ dispatch }) => next => action => {
  // 监听消息发送成功的事件
  if (action.type === 'DIRECT_LINE/POST_ACTIVITY_SUCCESS') {
    // 自动清除输入框
    dispatch({
      type: window.WebChat.createActionTypes().SEND_BOX_SET_SEND_BOX,
      payload: { text: '' }
    });
  }
  return next(action);
});

// 渲染Web Chat
window.WebChat.renderWebChat({
  directLine: window.WebChat.createDirectLine({ token: '你的DirectLine令牌' }),
  store: webChatStore
}, document.getElementById('webchat'));

注意事项

  • 不要依赖DOM选择器(比如你之前用的document.querySelector("[aria-label='Sendbox']")),因为Web Chat的DOM结构可能会随版本更新变化,官方的store action才是长期可靠的方式。
  • 确保你使用的Web Chat版本支持这些action(一般V4及以上版本都支持,如果你用的是旧版本,建议升级)。

内容的提问来源于stack exchange,提问作者Jegan Baskaran

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 21:47:41