Tampermonkey脚本失效:Gmail外发邮件警告提示功能排查
Gmail外部收件人警告Tampermonkey脚本修复方案
你写的脚本没效果主要是DOM匹配和事件逻辑的问题,以下是修复后的代码和问题说明:
原脚本的核心问题
- 选择器里用了HTML转义字符
",浏览器无法识别,导致找不到发送按钮和收件人元素 - 全局监听document的click事件,不管点什么都会触发检查,既低效又容易误判
- 确认发送后直接调用按钮click,会再次触发警告逻辑,陷入循环弹窗
- 收件人选择器
.vR[role="listitem"][email]不符合当前Gmail的DOM结构,拿不到收件人邮箱
修复后的脚本代码
// ==UserScript== // @name Gmail Warning Prompt // @namespace your-namespace // @version 1.1 // @description Display a warning prompt when sending emails to outside organizations in Gmail. // @match https://mail.google.com/* // @grant none // ==/UserScript== (function() { 'use strict'; let isConfirmed = false; // 标记是否已确认发送,避免循环弹窗 function checkExternalRecipients() { // 匹配所有收件人(包括收件人、抄送人、密送人) const recipients = Array.from(document.querySelectorAll('[data-email]')); return recipients.some(recipient => { const email = recipient.getAttribute('data-email'); return email && !email.endsWith('@yourorganization.com'); }); } function handleSendClick(event) { // 匹配发送按钮,适配Gmail的DOM结构 const sendButton = event.target.closest('div[role="button"][data-tooltip*="Send"]'); if (!sendButton || isConfirmed) return; const hasExternal = checkExternalRecipients(); if (hasExternal) { event.preventDefault(); event.stopPropagation(); const confirmation = confirm('警告:你正在发送邮件给外部组织,确定要继续吗?'); if (confirmation) { isConfirmed = true; // 触发原生发送逻辑 sendButton.click(); // 重置标记,避免影响下一次发送 setTimeout(() => isConfirmed = false, 1000); } } } // 监听点击事件,使用捕获阶段确保优先处理 document.addEventListener('click', handleSendClick, true); })();
关键修改说明
- 修复选择器:把所有转义的
"换成普通双引号,同时调整收件人选择器为[data-email],这是Gmail当前用来存储邮箱地址的稳定属性 - 精准触发逻辑:通过
event.target.closest()判断点击目标是否为发送按钮,避免无效触发 - 避免循环弹窗:新增
isConfirmed标记,确认发送后临时禁用检查,1秒后重置不影响下一次操作 - 阻止事件冒泡:使用
event.stopPropagation()防止原生发送逻辑被提前拦截
内容的提问来源于stack exchange,提问作者Ta sœur Ensemble
相关产品推荐
相关产品推荐

