前端JS嵌入AI聊天

思路

  1. 任何需要嵌入的页面,就是加载一个js
js 复制代码
  const ai = document.createElement('script')
  ai.src = process.env.VUE_APP_AI_EMBED_JS_URL + '/embed.js?sid=' + sid + '&token=' + token
  ai.async = true
  ai.defer = true
  ai.id = 'chat-script'

  document.body.appendChild(ai);
js 复制代码
<script
  async
  defer
  src="http://11.27.1.241/api/application/embed?protocol=http&host=11.27.1.241&token=f5c93503fc6c292e">
</script>
  1. embed.js的大体功能:读取url参数->创建浮动按钮->创建iframe容器->iframe.src=vue的聊天页面
js 复制代码
(function () {
    if (window.chatWindowEmbedded) return;
    window.chatWindowEmbedded = true;

    // 解析参数
    const script = document.currentScript;
    const params = new URLSearchParams(script.src.split('?')[1]);
    const sid = params.get('sid') || '';
    const token = params.get('token') || '';

    // 创建浮动按钮
    const floatBtn = document.createElement('div');
    floatBtn.innerHTML = '💬 AI';
    floatBtn.style.cssText = `
        position: fixed;
        bottom: 20px;
        right: 20px;
        background: #4285f4;
        color: white;
        padding: 12px 20px;
        border-radius: 30px;
        cursor: pointer;
        box-shadow: 0 2px 10px rgba(0,0,0,0.2);
        z-index: 9998;
        font-family: sans-serif;
        font-size: 14px;
    `;
    floatBtn.id = 'chat-button';

    // 创建 iframe 容器
    const iframeContainer = document.createElement('div');
    iframeContainer.id = 'chat-window-container';
    iframeContainer.style.cssText = `
        position: fixed;
        bottom: 80px;
        right: 20px;
        width: 400px;
        height: 600px;
        z-index: 9999;
        display: none;
        box-shadow: 0 0 20px rgba(0,0,0,0.1);
        border-radius: 12px;
        overflow: hidden;
        background: white;
    `;

    // 创建 iframe
    const iframe = document.createElement('iframe');
    iframe.id = 'chat-window-iframe';
    iframe.style.cssText = `
        width: 100%;
        height: 100%;
        border: none;
    `;
    iframeContainer.appendChild(iframe);

    // 添加关闭按钮
    const closeBtn = document.createElement('div');
    closeBtn.innerHTML = '×';
    closeBtn.style.cssText = `
        position: absolute;
        top: 10px;
        right: 10px;
        width: 24px;
        height: 24px;
        line-height: 24px;
        text-align: center;
        cursor: pointer;
        font-size: 20px;
        color: #888;
        z-index: 10000;
        background: rgba(255,255,255,0.8);
        border-radius: 50%;
    `;
    iframeContainer.appendChild(closeBtn);

    // 添加全屏按钮
    const fullscreenBtn = document.createElement('div');
    fullscreenBtn.innerHTML = '🔍';
    fullscreenBtn.style.cssText = `
        position: absolute;
        top: 10px;
        left: 10px;
        width: 24px;
        height: 24px;
        line-height: 24px;
        text-align: center;
        cursor: pointer;
        font-size: 20px;
        color: #888;
        z-index: 10000;
        background: rgba(255,255,255,0.8);
        border-radius: 50%;
    `;
    iframeContainer.appendChild(fullscreenBtn);

    document.body.appendChild(floatBtn);
    document.body.appendChild(iframeContainer);

    // 获取基础 URL
    const baseUrl = script.src.split('/').slice(0, -1).join('/');

    // 设置 iframe 的源 URL
    iframe.src = `${baseUrl}?sid=${sid}&token=${token}`;

    // 添加事件监听器
    let isOpen = false;
    floatBtn.addEventListener('click', () => {
        isOpen = !isOpen;
        iframeContainer.style.display = isOpen ? 'block' : 'none';

        if (isOpen) {
            iframe.contentWindow.postMessage('openChatWindow', '*')
        }
    });

    closeBtn.addEventListener('click', () => {
        isOpen = false;
        iframeContainer.style.display = 'none';
    });

    fullscreenBtn.addEventListener('click', () => {
        if (iframeContainer.style.width === '50vw' && iframeContainer.style.height === '100vh') {
            // 如果已经是全屏状态,恢复原始大小
            iframeContainer.style.width = '400px';
            iframeContainer.style.height = '600px';
            iframeContainer.style.bottom = '80px';
            iframeContainer.style.right = '20px';
            fullscreenBtn.innerHTML = '🔍'; // 改回放大镜图标
        } else {
            // 如果不是全屏状态,放大到屏幕的一半
            iframeContainer.style.width = '50vw';
            iframeContainer.style.height = '100vh';
            iframeContainer.style.bottom = '0';
            iframeContainer.style.right = '0';
            fullscreenBtn.innerHTML = '🔍'; // 改成缩小图标
        }
    });

    // 点击外部关闭
    document.addEventListener('click', (e) => {
        if (isOpen && !iframeContainer.contains(e.target) && e.target !== floatBtn && !e.target.closest('#chat-window-iframe')) {
            isOpen = false;
            iframeContainer.style.display = 'none';
        }
    });

    // 添加键盘快捷键(ESC关闭)
    document.addEventListener('keydown', (e) => {
        if (isOpen && e.key === 'Escape') {
            isOpen = false;
            iframeContainer.style.display = 'none';
        }
    });

    // 监听来自 iframe 的消息(用于关闭等操作)
    window.addEventListener('message', (event) => {
        // 确保消息来自可信源
        if (event.origin !== new URL(baseUrl).origin) return;

        if (event.data === 'closeChatWindow') {
            isOpen = false;
            iframeContainer.style.display = 'none';
        }
    });
})();
  1. 点击悬浮按钮打开聊天页面事件
js 复制代码
    let isOpen = false;
    floatBtn.addEventListener('click', () => {
        isOpen = !isOpen;
        iframeContainer.style.display = isOpen ? 'block' : 'none';

        if (isOpen) {
            iframe.contentWindow.postMessage('openChatWindow', '*')
        }
    });
  1. vue聊天项目main.js,单独加载vue文件
js 复制代码
const isEmbedded = window.chatWindowEmbedded && !window.location.hostname.includes('localhost');
if (!isEmbedded) {
    createApp(App).use(store).use(router).mount('#app')
} else {
    console.log('Running in embedded mode');

    import('@/components/ChatWindow.vue').then(module => {
        window.ChatWindow = module.default;
    });
}
  1. 相应的vue文件,设置消息监听
js 复制代码
onMounted(() => {
  messages.push({
    role: 'ai',
    content: '您好,我是您的专属AI助手,我可以帮您分析客户相关数据并进行总结,比如"综合报告","征信简报","流水简报"等。',
    displayContent: '您好,我是您的专属AI助手,我可以帮您分析客户相关数据并进行总结,比如"综合报告","征信简报","流水简报"等。',
    isStreaming: false,
    timestamp: new Date()
  });
  scrollToBottom();

  window.addEventListener('message', handleParentMessage);
});
相关推荐
艾莉丝努力练剑11 分钟前
【AI接入大模型SDK】解决接口连接异常问题
前端·c++·人工智能·学习·ai·架构
Nayana12 分钟前
《Web 到 HarmonyOS》-- 布局与样式:CSS → Column / $r
前端
徐小夕1 小时前
折腾一年,我们正式发布 JitOffice:一款跑在浏览器里的 AI Office
前端·vue.js·github
恋猫de小郭2 小时前
Flutter A2UI 1.0 ,原来的 genui 也正式换成了这一套 SDK 了
android·前端·flutter
zhanlang02172 小时前
HTML 零基础入门到企业实战全套教程【第九章】企业开发规范与兼容适配|9.1 主流浏览器兼容问题与解决方案
前端·html
小码哥0682 小时前
短剧平台源码定制交付:批量导入剧集与媒体资源校验流程
前端·vue.js·媒体·短剧小程序·短剧系统·抖音短剧
晓得迷路了2 小时前
栗子前端技术周刊第 155 期 - 2026 HTML 现状调查报告、Solid 2.0...
前端·javascript·webpack
艾莉丝努力练剑2 小时前
【AI接入大模型SDK】Markdown格式解析
前端·c++·人工智能·学习·ai·架构
LinXunFeng3 小时前
A2UI 1.0 详解:让 AI 生成 Flutter 界面,还不怕它乱写
前端·flutter·agent
AI算力12 小时前
让安全驾驶有“AI”相伴|腾视科技DMS视频监控一体机,守护每一次出行
人工智能·科技·ai·车载终端·ai算力·车载智能终端·车载dvr