如何通过Chrome扩展注入JS修改网页版Teams聊天框内容并发送?
解决Teams CKEditor聊天框自动填充并发送的Chrome扩展方案
一、扩展结构与配置
创建Chrome扩展需包含两个核心文件:manifest.json(扩展配置)和content.js(注入到Teams页面的脚本)。
1. 编写manifest.json
{ "manifest_version": 3, "name": "Teams自动发送助手", "version": "1.0", "content_scripts": [ { "matches": ["https://teams.microsoft.com/*"], "js": ["content.js"], "run_at": "document_idle" } ], "permissions": [] }
matches指定脚本注入的Teams页面范围run_at设为document_idle,确保页面核心元素加载完成后执行脚本
二、编写内容脚本content.js
直接操作CKEditor实例(而非修改DOM)填充内容,再触发发送按钮:
// 监听页面加载完成,确保编辑器初始化 document.addEventListener('DOMContentLoaded', () => { // 定时器延迟执行,适配Teams动态加载元素 setTimeout(() => { // 定位CKEditor容器 const editorContainer = document.querySelector('div[data-tid="ckeditor"]'); if (!editorContainer) { console.log('未找到CKEditor容器'); return; } // 获取CKEditor实例(Teams通过dataset.editorId绑定实例) const editorId = editorContainer.dataset.editorId; const editor = window.CKEDITOR?.instances[editorId]; if (!editor) { console.log('未获取到CKEditor实例'); return; } // 设置编辑器内容 editor.setData('Hello World'); // 定位并点击发送按钮 const sendButton = document.querySelector('button[data-tid="send-message-button"]') || document.querySelector('button[aria-label="发送"]'); if (sendButton) { sendButton.click(); console.log('消息已发送'); } else { console.log('未找到发送按钮'); } }, 3000); // 延迟时间可根据页面加载速度调整 });
三、优化建议(可选)
- 替换定时器为
MutationObserver,监听编辑器元素出现,更精准触发:
const observer = new MutationObserver((mutations) => { for (const mutation of mutations) { if (mutation.addedNodes.length) { const editorContainer = document.querySelector('div[data-tid="ckeditor"]'); if (editorContainer) { // 执行填充和发送逻辑(同上述代码) observer.disconnect(); // 找到元素后停止监听 } } } }); observer.observe(document.body, { childList: true, subtree: true });
- 若Teams更新元素属性,需调整选择器(比如发送按钮的
data-tid或aria-label)
内容的提问来源于stack exchange,提问作者Vinzzz
相关产品推荐
相关产品推荐

