如何在Chrome扩展中实现Google Calendar事件打开/更新触发函数?
Chrome扩展实现Google Calendar事件触发的方案
因为Chrome扩展是基于网页注入的方式工作,没法像Google Apps Script那样直接用官方提供的触发器API,得通过内容脚本监听网页DOM变化来实现类似效果,以下是具体步骤和代码示例:
1. 配置扩展Manifest(v3版本)
首先创建manifest.json,声明内容脚本的匹配规则:
{ "manifest_version": 3, "name": "Calendar Event Handler", "version": "1.0", "content_scripts": [ { "matches": ["https://calendar.google.com/calendar/*"], "js": ["content.js"], "run_at": "document_idle" } ], "permissions": [] }
2. 编写内容脚本监听事件
Google Calendar是单页应用,用MutationObserver监听DOM变化来捕获事件打开/更新行为,创建content.js文件:
// 监听页面整体DOM变化 const bodyObserver = new MutationObserver((mutations) => { mutations.forEach(mutation => { // 检测事件详情对话框(打开事件时出现) const eventDialog = document.querySelector('[role="dialog"][aria-label*="Event"]'); if (eventDialog) { // 触发事件打开逻辑 handleEventOpen(eventDialog); // 监听对话框内的内容更新(编辑事件时触发) setupDialogUpdateListener(eventDialog); // 暂时停止监听body,避免重复触发 bodyObserver.disconnect(); // 监听对话框关闭,恢复body监听 const closeBtn = eventDialog.querySelector('[aria-label="Close"]'); closeBtn?.addEventListener('click', () => { bodyObserver.observe(document.body, { childList: true, subtree: true }); }); } }); }); // 启动body监听 bodyObserver.observe(document.body, { childList: true, subtree: true }); // 事件打开时执行的自定义函数 function handleEventOpen(dialog) { console.log('事件已打开'); // 示例:获取事件标题 const title = dialog.querySelector('[aria-label="Title"] input')?.value; console.log('事件标题:', title); } // 监听对话框内的内容更新 function setupDialogUpdateListener(dialog) { const dialogObserver = new MutationObserver((mutations) => { mutations.forEach(mutation => { // 检测到内容变化时触发更新逻辑 if (mutation.type === 'childList' || mutation.type === 'attributes') { handleEventUpdate(dialog); } }); }); dialogObserver.observe(dialog, { childList: true, subtree: true, attributes: true }); } // 事件更新时执行的自定义函数 function handleEventUpdate(dialog) { console.log('事件内容已更新'); // 示例:获取更新后的事件标题 const updatedTitle = dialog.querySelector('[aria-label="Title"] input')?.value; console.log('更新后的标题:', updatedTitle); }
注意事项
- Google Calendar的DOM类名/属性可能会更新,需要自己用Chrome DevTools查看当前页面的元素选择器,调整代码中的选择器
- 如果需要和扩展后台脚本通信,可使用
chrome.runtime.sendMessage传递数据 - 测试时,在Chrome扩展管理页面选择「加载已解压的扩展」,选中你的扩展文件夹即可
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

