Я использую Microsoft/BotFramework-WebChat, но у меня возникают проблемы с его правильной прокруткой.
Часто, когда бот отвечает, пользователю приходится вручную прокручивать лог чата в самый низ.
Я не могу найти документацию о хуках, которые позволили бы мне вызывать API для прокрутки.
Есть ли способ сделать так, чтобы окно чата прокручивалось автоматически?
HTML:
<div id = "bot-button" style = "display:none" >
<p id = "need-help" class = "triangle-isosceles">Hey! Need any help?</p>
<div id = "bot-open" token = "temptoken">
<span>
<img id = "avatar" src = "/img/avatar.png"/>
<i id = "message-count">2</i>
</span>
</div>
<div id = "bot-close"><img src = "/img/close.png" height = "20px"/>Close</div>
<div id = "webchat" role = "main"></div>
</div>
<script src = "https://cdn.botframework.com/botframework-webchat/master/webchat.js"></script>
<script src = "/js/chat.js"></script>
JavaScript:
(async function () {
// In this demo, we are using Direct Line token from MockBot.
// To talk to your bot, you should use the token exchanged using your Direct Line secret.
// You should never put the Direct Line secret in the browser or client app.
// https://docs.microsoft.com/en-us/azure/bot-service/rest-api/bot-framework-rest-direct-line-3-0-authentication
var bearer_token = document.getElementById("bot-open").getAttribute("token");
const res = await fetch('https://directline.botframework.com/v3/directline/tokens/generate', {
method: 'POST',
headers: {
"Authorization": "Bearer " + bearer_token
}
});
const {
token
} = await res.json();
// We are using a customized store to add hooks to connect event
const store = window.WebChat.createStore({}, ({
dispatch
}) => next => action => {
if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
// When we receive DIRECT_LINE/CONNECT_FULFILLED action, we will send an event activity using WEB_CHAT/SEND_EVENT
dispatch({
type: 'WEB_CHAT/SEND_EVENT',
payload: {
name: 'webchat/join',
value: {
language: window.navigator.language
}
}
});
}
return next(action);
});
const styleOptions = {
bubbleBackground: 'rgba(0, 0, 255, .1)',
bubbleFromUserBackground: 'rgba(0, 255, 0, .1)',
hideUploadButton: true,
botAvatarInitials: 'DA',
};
window.WebChat.renderWebChat({
directLine: window.WebChat.createDirectLine({
token
}),
userID: guid(),
store,
styleOptions
}, document.getElementById('webchat'));
sizeBotChat();
document.querySelector('#webchat > *').focus();
})().catch(err => console.error(err));
function sizeBotChat() {
let bot_container = document.getElementById("bot-button");
if (isMobileDevice()) {
bot_container.style.width = "100%";
bot_container.style.bottom = "0px";
bot_container.style.right = "0px";
let max_height = screen.height - 50;
document.getElementById("webchat").style.maxHeight = max_height + "px";
console.info(screen.height);
} else {
bot_container.style.width = "400px";
bot_container.style.right = "50px";
document.getElementById("webchat").style.maxHeight = "400px";
}
}
CSS(загружается с помощью javascript, вставляющего ссылку в элемент head):
.triangle-isosceles {
position: relative;
padding: 15px;
color: black;
background: white;
border-radius: 10px;
}
/* creates triangle */
.triangle-isosceles:after {
content: "";
display: block;
/* reduce the damage in FF3.0 */
position: absolute;
bottom: -15px;
right: 30px;
width: 0;
border-width: 15px 15px 0;
border-style: solid;
border-color: white transparent;
}
#avatar {
height: 50px;
}
#need-help {
display: none;
}
/* based on badge progress-bar-danger from bootstrap */
#message-count {
display: inline-block;
min-width: 10px;
padding: 3px 7px 3px 7px;
font-size: 12px;
font-weight: 700;
line-height: 1;
color: white;
text-align: center;
white-space: nowrap;
vertical-align: middle;
border-radius: 10px;
background-color: #d9534f;
position: relative;
top: -20px;
right: 20px;
}
#bot-button {
position: fixed;
bottom: 50px;
right: 0px;
width: 100%;
}
#bot-open {
height: 50px;
width: 100%;
text-align: right;
}
#bot-close {
background-color: blue;
background-image: url("https://localhost/img/avatar.png");
background-repeat: no-repeat;
color: white;
height: 22px;
display: none;
height: 50px;
padding: 15px 15px 0 0;
text-align: right;
vertical-align: middle;
}
/* hide chat on load */
#webchat {
display: none;
max-height: 400px;
overflow: scroll;
}
#webchat div.row.message {
margin: 0;
}






Разработчики разработали WebChat для прокрутки разговора вниз, если пользователь не прокручивал вверх. Если пользователь прокрутил вверх, должна быть кнопка «Новое сообщение», которая появляется в правом нижнем углу чата, когда бот отправляет новое сообщение.
Вы можете изменить это поведение с помощью пользовательского промежуточного программного обеспечения (которое, похоже, у вас уже есть) и прокручивая последний элемент в диалоге, когда пользователь получает сообщение от бота. См. фрагмент кода ниже.
const store = window.WebChat.createStore(
{},
({ dispatch }) => next => action => {
if (action.type === 'DIRECT_LINE/INCOMING_ACTIVITY') {
document.querySelector('ul[role = "list"]').lastChild.scrollIntoView({behavior: 'smooth', block: 'start'});
}
...
return next(action);
}
);
Надеюсь это поможет!
Работает отлично, спасибо! Мне просто нужно было проверить, что "document.querySelector('ul[role = "list"]').lastChild" не равен нулю перед прокруткой, потому что событие срабатывает до того, как появились элементы. Большое спасибо за помощь!
Можете ли вы опубликовать свой код (включая CSS) для вашего веб-чата?