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

如何用原生JavaScript向Bot Framework编程发送消息?

原生JavaScript实现Bot Framework Web Chat编程式发送消息

步骤1:调整初始化脚本,暴露全局可访问的Store和DirectLine实例

修改你加载Web Chat的脚本,将store和directLine对象挂载到window上,让外部按钮能访问这些核心实例:

(async function() {
    const res = await fetch("https://MYURLPRIVATE/api/directline/token", {
        "method": "GET"
    });
    const { token } = await res.json();
    console.log(token);
    var styleOptions = {
        hideUploadButton: true,
        timestampFormat: 'absolute'
    };

    // 将store和directLine保存到全局window对象
    window.webChatStore = window.WebChat.createStore({}, ({ dispatch }) => next => action => {
        return next(action);
    });
    window.webChatDirectLine = window.WebChat.createDirectLine({ token });

    window.WebChat.renderWebChat({
        directLine: window.webChatDirectLine,
        locale: 'it-IT',
        styleOptions,
        store: window.webChatStore
    }, document.getElementById('chatTranscript'));
    document.querySelector('#chatTranscript > *').focus();
})().catch(err => insertError(err))

步骤2:绑定按钮点击事件,实现编程式发消息

推荐使用Web Chat的Store Dispatch方式,这种方式会自动同步UI状态,确保消息正确显示在聊天窗口中:

// 假设你的按钮id为sendMessageBtn
document.getElementById('sendMessageBtn').addEventListener('click', () => {
    const messageText = 'hi';
    // 通过dispatch触发发送消息的action
    window.webChatStore.dispatch({
        type: 'WEB_CHAT/SEND_MESSAGE',
        payload: { text: messageText }
    });
});

备选方案:直接通过DirectLine实例发送活动

如果需要更底层的控制,可以调用DirectLine的postActivity方法直接和Bot后端通信,Web Chat通常会自动同步消息到UI:

document.getElementById('sendMessageBtn').addEventListener('click', async () => {
    const messageText = 'hi';
    try {
        await window.webChatDirectLine.postActivity({
            type: 'message',
            text: messageText,
            from: { id: 'user', name: '用户' } // 用户标识可根据实际场景调整
        });
    } catch (error) {
        console.error('消息发送失败:', error);
    }
});

为什么模拟输入框填充和点击无效?

Web Chat的输入框是受控组件,内部状态由框架自身管理,直接操作DOM修改输入框内容不会同步到内部状态,因此模拟点击发送按钮也无法触发消息发送逻辑,必须通过官方提供的API(Store或DirectLine实例)来操作。

内容的提问来源于stack exchange,提问作者Mirko Cianfarani

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 14:30:38