如何禁用Microsoft BotFramework WebChat欢迎卡片渲染时的自动滚屏至底部功能?
解决BotFramework WebChat欢迎消息自动滚屏问题
方法1:通过scrollToEndBehavior配置全局滚动策略
在调用renderWebChat初始化时,利用scrollToEndBehavior选项自定义滚动行为,针对欢迎消息禁用自动滚屏:
window.WebChat.renderWebChat({ directLine: window.WebChat.createDirectLine({ token: 'YOUR_DIRECT_LINE_TOKEN' }), scrollToEndBehavior: (behavior, action) => { // 判断当前消息是否为欢迎消息,可根据实际文本/标识调整条件 if (action.payload?.activity?.text?.includes('欢迎')) { return 'preserve'; // 保持当前滚动位置,不自动滚到底部 } return 'auto'; // 其他消息保持默认自动滚屏 } }, document.getElementById('webchat'));
'preserve':强制保持当前滚动位置,不会自动滚动'auto':默认行为,消息发送后自动滚到底部- 也可直接设置固定值
scrollToEndBehavior: 'preserve',全局禁用自动滚屏
方法2:通过Store Middleware精准拦截欢迎消息
如果需要更精细的控制,可借助WebChat的Store Middleware拦截入站消息,针对欢迎消息触发阻止滚动的指令:
const store = window.WebChat.createStore({}, ({ dispatch }) => next => action => { if (action.type === 'DIRECT_LINE/INCOMING_ACTIVITY') { const activity = action.payload.activity; // 根据消息特征判断是否为欢迎消息,比如type、自定义channelData等 if (activity.type === 'message' && activity.text === '欢迎使用我们的服务') { // 发送指令保持当前滚动位置 dispatch({ type: 'WEB_CHAT/SCROLL_TO_END', payload: { behavior: 'preserve' } }); } } return next(action); }); window.WebChat.renderWebChat({ directLine: window.WebChat.createDirectLine({ token: 'YOUR_DIRECT_LINE_TOKEN' }), store }, document.getElementById('webchat'));
方法3:手动调整滚动位置(兜底方案)
若上述配置不生效,可通过DOM监听手动将滚动条定位到欢迎消息顶部:
const webChatContainer = document.getElementById('webchat'); const observer = new MutationObserver((mutations) => { mutations.forEach(mutation => { if (mutation.addedNodes.length) { // 匹配包含欢迎文本的消息容器 const welcomeMsg = webChatContainer.querySelector('.wc-message-content:contains("欢迎")'); if (welcomeMsg) { // 将滚动条定位到消息顶部 welcomeMsg.scrollIntoView({ behavior: 'smooth', block: 'start' }); observer.disconnect(); // 仅执行一次后停止监听 } } }); }); // 监听WebChat容器的DOM变化 observer.observe(webChatContainer, { childList: true, subtree: true });
注意事项
- 请根据实际欢迎消息的文本、类型或自定义标识调整判断条件,确保精准匹配
- 若使用旧版本WebChat,部分配置项可能不支持,建议升级至最新稳定版
内容的提问来源于stack exchange,提问作者userbin
相关产品推荐
相关产品推荐

