Bot Framework Web Chat 3升4后调用renderWebChat致自定义botTitleBar丢失
问题根因
- Web Chat 4的
renderWebChat方法渲染时会完全清空目标容器内的所有已有子节点,你预先放在#botDiv中的botTitleBar节点直接被覆盖清除,所以DOM中找不到该元素。 - 你同时引入了Web Chat 3和Web Chat 4两个版本的JS、CSS资源,版本冲突会额外导致渲染异常。
解决方案
步骤1:清理冲突的资源引用
删除页面头部Web Chat 3的旧资源,仅保留Web Chat 4的资源即可:
<!-- 移除以下两行Web Chat 3的旧资源 --> <!-- <link href="https://cdn.botframework.com/botframework-webchat/latest/botchat.css" rel="stylesheet" /> --> <!-- <script src="https://cdn.botframework.com/botframework-webchat/latest/botchat.js"></script> --> <!-- 仅保留以下Web Chat 4的资源和你的自定义样式 --> <link crossorigin="anonymous" href="https://cdn.botframework.com/botframework-webchat/latest/webchat.css" rel="stylesheet" /> <link rel="stylesheet" href="~/css/botchatey.css"> <script crossorigin="anonymous" src="https://cdn.botframework.com/botframework-webchat/latest/webchat.js"></script>
步骤2:调整DOM结构,分离标题栏和Web Chat渲染容器
不要把自定义标题栏放在Web Chat的渲染容器内,新增外层容器同时承载标题栏和独立的Web Chat渲染节点,替换你原有创建DOM的代码:
// 创建外层总容器,原来的botDiv逻辑挪到外层 const botContainer = document.createElement('div'); botContainer.id = 'botDiv'; botContainer.style = 'width: 400px; height: 0px; margin:10px; position: fixed; bottom: 0; right:0; z-index: 1000; background-color:#252525; border:1px solid #252525;'; // 插入自定义标题栏 const titleBar = document.createElement('div'); titleBar.id = 'botTitleBar'; titleBar.style = 'height: 40px; width: 400px; cursor: pointer; background-color:#FFE600;'; botContainer.appendChild(titleBar); // 新增独立的Web Chat渲染容器,和标题栏平级 const chatContainer = document.createElement('div'); chatContainer.id = 'botChatContainer'; chatContainer.style = 'height: calc(100% - 40px); overflow: hidden;'; // 高度自动减去标题栏的40px botContainer.appendChild(chatContainer); document.body.appendChild(botContainer);
步骤3:修改Web Chat挂载目标
将renderWebChat的挂载节点从原来的#botDiv改为专门的#botChatContainer:
window.WebChat.renderWebChat({ directLine: window.WebChat.createDirectLine({ token }), webSpeechPonyfillFactory: window.WebChat.createBrowserWebSpeechPonyfillFactory(), store, userID: `You`, username: 'Web Chat User', locale: 'en-US', styleOptions // 挂载到独立的渲染容器,不会影响外层的标题栏 }, document.getElementById('botChatContainer')); // 聚焦逻辑同步调整 document.querySelector('#botChatContainer > *').focus();
步骤4:修正点击事件选择器
你原有点击事件中匹配的#chatbotheader和实际标题栏的id=botTitleBar不一致,同步修改即可:
document.querySelector('body').addEventListener('click', function (e) { e.target.matches = e.target.matches || e.target.msMatchesSelector; // 替换为实际的标题栏ID if (e.target.matches('#botTitleBar')) { const botDiv = document.querySelector('#botDiv'); botDiv.style.height = "0px"; document.getElementById("mychat").style.display = "block"; }; });
修改完成后标题栏不会再被Web Chat的渲染逻辑覆盖,最大化最小化功能也可正常运行。
内容的提问来源于stack exchange,提问作者Ricardo Jahn
相关产品推荐
相关产品推荐

