您可以参考以下示例代码在您的网页中动态添加botchat.css和botchat.js文件,并动态发起botchat。
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<input id="btninit" type="button" value="startchat" onclick="initiateChat()" />
<br />
<div id="mybot" />
</body>
</html>
<script>
function initiateChat() {
addCSS("https://cdn.botframework.com/botframework-webchat/latest/botchat.css");
addScript("https://cdn.botframework.com/botframework-webchat/latest/botchat.js");
setTimeout(function () {
BotChat.App({
directLine: { secret: 'your_directline_secret' },
user: { id: '1234', firstname: 'firstname_here', lastname: 'lastname_here' },
bot: { id: 'your_bot_id' },
resize: 'detect'
}, document.getElementById("mybot"))
}, 3000);
}
// add CSS file
function addCSS(filename) {
var head = document.getElementsByTagName('head')[0];
var style = document.createElement('link');
style.href = filename;
style.type = 'text/css';
style.rel = 'stylesheet';
head.appendChild(style);
}
// add script file
function addScript(filename) {
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.src = filename;
script.type = 'text/javascript';
head.insertBefore(script, document.getElementsByTagName("script")[0]);
}
</script>
另外,要加载一个JavaScript文件,也可以使用jQuery.getScript() menthod,然后在成功回调函数中发起botchat。
var url = "https://cdn.botframework.com/botframework-webchat/latest/botchat.js";
$.getScript(url, function () {
BotChat.App({
directLine: { secret: 'your_directline_secret' },
user: { id: '1234', firstname: 'firstname_here', lastname: 'lastname_here' },
bot: { id: 'your_bot_id' },
resize: 'detect'
}, document.getElementById("mybot"))
});
测试结果: