如何让基于OpenAI API与Django开发的Chatbot支持嵌入第三方网站?
实现轻量级聊天机器人嵌入方案(替代iframe)
核心思路
开发一个可嵌入的独立JS脚本,让其他网站仅需引入少量代码就能按需唤起聊天窗口,解决iframe样式简陋、常驻占用页面空间的问题,达到类似Botpress的集成体验。
具体实现步骤
1. 后端接口适配
在你的Django项目中,对外开放聊天所需的API接口(如发送消息、获取回复),同时配置跨域支持确保其他网站能正常调用:
# settings.py中配置跨域依赖django-cors-headers INSTALLED_APPS = [ # ...其他已有应用 'corsheaders', ] MIDDLEWARE = [ # ...其他已有中间件 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ] # 生产环境建议替换为指定可信域名列表 CORS_ALLOW_ALL_ORIGINS = True
2. 编写嵌入用前端脚本
创建chatbot-embed.js文件,实现聊天窗口的按需显隐、样式渲染和后端交互逻辑:
(function() { // 创建悬浮触发按钮 const chatToggleBtn = document.createElement('button'); chatToggleBtn.innerHTML = '💬 聊天助手'; chatToggleBtn.style.cssText = ` position: fixed; bottom: 20px; right: 20px; padding: 12px 20px; border: none; border-radius: 25px; background: #007bff; color: #fff; cursor: pointer; font-size: 14px; box-shadow: 0 2px 10px rgba(0,0,0,0.15); z-index: 9999; transition: background 0.2s; `; chatToggleBtn.onmouseover = () => chatToggleBtn.style.background = '#0056b3'; chatToggleBtn.onmouseout = () => chatToggleBtn.style.background = '#007bff'; document.body.appendChild(chatToggleBtn); // 创建聊天窗口容器 const chatContainer = document.createElement('div'); chatContainer.style.cssText = ` position: fixed; bottom: 80px; right: 20px; width: 350px; height: 500px; border-radius: 10px; box-shadow: 0 4px 20px rgba(0,0,0,0.2); background: #fff; display: none; flex-direction: column; z-index: 9999; `; document.body.appendChild(chatContainer); // 聊天窗口头部 const chatHeader = document.createElement('div'); chatHeader.innerHTML = ` <div style="display: flex; justify-content: space-between; align-items: center; padding: 15px; border-bottom: 1px solid #eee;"> <h3 style="margin: 0; font-size: 16px;">聊天助手</h3> <button id="chatCloseBtn" style="border: none; background: transparent; font-size: 18px; cursor: pointer;">×</button> </div> `; chatContainer.appendChild(chatHeader); // 消息列表区域 const messageList = document.createElement('div'); messageList.style.cssText = ` flex: 1; padding: 15px; overflow-y: auto; background: #f8f9fa; `; chatContainer.appendChild(messageList); // 输入区域 const inputWrap = document.createElement('div'); inputWrap.style.cssText = ` display: flex; padding: 10px; border-top: 1px solid #eee; `; const msgInput = document.createElement('input'); msgInput.type = 'text'; msgInput.placeholder = '输入消息...'; msgInput.style.cssText = ` flex: 1; padding: 8px 12px; border: 1px solid #ddd; border-radius: 20px; margin-right: 8px; outline: none; `; const sendBtn = document.createElement('button'); sendBtn.innerHTML = '发送'; sendBtn.style.cssText = ` padding: 8px 16px; border: none; border-radius: 20px; background: #007bff; color: #fff; cursor: pointer; transition: background 0.2s; `; sendBtn.onmouseover = () => sendBtn.style.background = '#0056b3'; sendBtn.onmouseout = () => sendBtn.style.background = '#007bff'; inputWrap.appendChild(msgInput); inputWrap.appendChild(sendBtn); chatContainer.appendChild(inputWrap); // 窗口显隐切换逻辑 const toggleChatWindow = () => { chatContainer.style.display = chatContainer.style.display === 'none' ? 'flex' : 'none'; }; chatToggleBtn.addEventListener('click', toggleChatWindow); document.getElementById('chatCloseBtn').addEventListener('click', toggleChatWindow); // 发送消息与获取回复逻辑 const sendMessage = async () => { const content = msgInput.value.trim(); if (!content) return; // 添加用户消息到列表 appendMessage(content, 'user'); msgInput.value = ''; // 调用后端API try { const res = await fetch('https://你的Railway部署域名/api/chat/', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({message: content}) }); const data = await res.json(); appendMessage(data.reply, 'bot'); } catch (err) { appendMessage('抱歉,暂时无法回复,请稍后再试。', 'bot'); } }; // 消息追加工具函数 const appendMessage = (content, sender) => { const msgDiv = document.createElement('div'); const align = sender === 'user' ? 'flex-end' : 'flex-start'; const bgColor = sender === 'user' ? '#007bff' : '#fff'; const textColor = sender === 'user' ? '#fff' : '#333'; msgDiv.style.cssText = ` display: flex; justify-content: ${align}; margin-bottom: 10px; `; msgDiv.innerHTML = ` <div style=" max-width: 70%; padding: 8px 12px; border-radius: 15px; background: ${bgColor}; color: ${textColor}; box-shadow: 0 1px 3px rgba(0,0,0,0.1); ">${content}</div> `; messageList.appendChild(msgDiv); messageList.scrollTop = messageList.scrollHeight; }; // 绑定发送事件 sendBtn.addEventListener('click', sendMessage); msgInput.addEventListener('keypress', e => e.key === 'Enter' && sendMessage()); })();
3. 托管嵌入脚本
将上述JS文件上传到你的Railway项目静态资源目录(或其他静态文件托管服务),获取可公开访问的URL。
4. 提供集成代码
其他网站只需在页面末尾添加以下代码即可完成集成:
<!-- 引入聊天机器人脚本 --> <script src="https://你的脚本托管地址/chatbot-embed.js"></script>
如果需要自定义配置(如按钮文字、颜色),可扩展脚本支持全局配置参数:
<script> // 自定义配置示例 window.chatbotConfig = { buttonText: '在线客服', buttonColor: '#28a745' }; </script> <script src="https://你的脚本托管地址/chatbot-embed.js"></script>
5. 可选优化方向
- 添加消息加载状态提示
- 支持localStorage存储聊天历史
- 适配移动端自动调整窗口尺寸
- 增加消息发送失败重试机制
内容的提问来源于stack exchange,提问作者iulian
相关产品推荐
相关产品推荐

