You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Gmail自动点击“发送为”箭头的Tampermonkey脚本故障排查

解决Gmail Tampermonkey脚本的两个问题

问题1:MutationObserver仅触发一次

你的waitForElement用Promise封装,找到第一个匹配元素就resolve并断开观察者,因此只能响应首次打开的撰写窗口。要持续监听所有撰写窗口的打开,需调整逻辑:

  • 放弃一次性Promise的写法,让MutationObserver持续运行
  • 增加重复过滤机制,避免对同一个撰写窗口重复执行操作

问题2:无法触发按钮点击

Gmail的交互元素依赖完整的用户事件序列,且原选择器可能不够精准,直接调用click()或简单MouseEvent无法触发内部绑定的事件。解决方案:

  • 确保选中真正可交互的目标元素(通过aria-label等属性精准定位)
  • 模拟完整的用户点击事件链(mousedown→mouseup→click),并设置事件的冒泡和可取消属性

修改后的完整脚本

// ==UserScript==
// @name         Auto Click "Send As" Arrow in Gmail Compose
// @namespace    http://tampermonkey.net/
// @version      0.2
// @description  Automatically clicks the "Send As" dropdown arrow when Gmail compose window opens
// @author       You
// @match        http*://mail.google.com/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=tampermonkey.net
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    // 用WeakSet记录已处理的撰写窗口,避免重复操作且自动回收内存
    const processedWindows = new WeakSet();

    const observer = new MutationObserver(() => {
        // 获取所有打开的撰写窗口
        const composeWindows = document.querySelectorAll('.nH.Hd[role=dialog]');
        
        composeWindows.forEach(window => {
            if (processedWindows.has(window)) return;
            
            // 精准定位"发送为"箭头(根据Gmail语言调整aria-label内容)
            const sendAsArrow = window.querySelector('.J-J5-Ji.J-JN-M-I-JG[aria-label="发送为"]');
            
            if (sendAsArrow) {
                // 模拟完整的用户点击事件链
                const fireEvent = (type) => {
                    sendAsArrow.dispatchEvent(new MouseEvent(type, {
                        bubbles: true,
                        cancelable: true,
                        view: window
                    }));
                };
                
                fireEvent('mousedown');
                fireEvent('mouseup');
                fireEvent('click');
                
                console.log("自动点击了'发送为'箭头");
                processedWindows.add(window);
            }
        });
    });

    // 启动观察者,监听整个文档的子树变化
    observer.observe(document.body, {
        childList: true,
        subtree: true
    });
})();

关键修改说明

  1. 持续监听机制:改用全局MutationObserver持续检测撰写窗口,WeakSet自动管理已处理窗口,避免重复执行
  2. 精准元素定位:通过aria-label属性锁定目标按钮,避免选择到无关元素
  3. 完整事件模拟:按真实用户操作顺序触发事件,确保Gmail内部的交互逻辑被正确触发
  4. 内存友好:WeakSet存储已处理窗口,窗口关闭后自动被垃圾回收,无内存泄漏风险

内容的提问来源于stack exchange,提问作者dragonmnl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 05:46:10