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

如何让浏览器扩展监听邮件编辑时收件人地址字段的变更?

监听邮件编辑时收件人地址变更的解决方案

针对你的需求,分两种场景给出可行方案:

一、Thunderbird WebExtension 场景

如果是开发Thunderbird的邮件扩展,优先使用**browser.compose.onRecipientsChanged**API(Thunderbird 91及以上版本支持),这个事件专门监听收件人(to/cc/bcc)的添加、修改或删除操作,触发时机稳定,能覆盖编辑完成后的状态:

// 监听收件人变更事件
browser.compose.onRecipientsChanged.addListener((details) => {
  // 提取to字段的收件人列表
  const updatedToRecipients = details.recipients.to;
  console.log("收件人已更新:", updatedToRecipients);
  
  // 可结合之前存储的收件人列表,判断是添加还是修改操作
  // 示例:对比前后列表差异
  // const previousRecipients = getStoredRecipients();
  // const added = updatedToRecipients.filter(r => !previousRecipients.includes(r));
});

如果需要兼容更低版本的Thunderbird(无onRecipientsChanged),可以结合browser.compose.onComposeStateChanged和定时轮询browser.compose.getComposeDetails的方式:

let previousToRecipients = [];

// 监听编辑状态变化
browser.compose.onComposeStateChanged.addListener(async (tab) => {
  const details = await browser.compose.getComposeDetails(tab.id);
  const currentTo = details.to;
  
  // 对比前后列表,判断是否有变更
  if (JSON.stringify(currentTo) !== JSON.stringify(previousToRecipients)) {
    console.log("收件人变更:", currentTo);
    previousToRecipients = [...currentTo];
  }
});

// 额外添加定时轮询,弥补事件触发的遗漏
setInterval(async () => {
  const tabs = await browser.tabs.query({active: true, currentWindow: true});
  for (const tab of tabs) {
    if (tab.type === 'messageCompose') {
      const details = await browser.compose.getComposeDetails(tab.id);
      const currentTo = details.to;
      if (JSON.stringify(currentTo) !== JSON.stringify(previousToRecipients)) {
        console.log("收件人变更(轮询检测):", currentTo);
        previousToRecipients = [...currentTo];
      }
    }
  }
}, 1000);

二、浏览器扩展(针对网页端邮件,如Gmail)

网页端邮件没有统一的扩展API,需要通过DOM监听+MutationObserver来实现:
以Gmail为例,监听收件人输入区域的内容变化:

// 动态检测收件人容器(Gmail的to字段容器有特定aria-label)
function observeRecipients() {
  const toContainer = document.querySelector('div[aria-label="收件人"]');
  if (!toContainer) {
    // 容器未加载,延迟重试
    setTimeout(observeRecipients, 500);
    return;
  }

  let previousRecipients = [];
  const observer = new MutationObserver((mutations) => {
    // 获取当前所有收件人邮箱
    const currentRecipients = Array.from(toContainer.querySelectorAll('span[email]'))
      .map(el => el.getAttribute('email'));
    
    if (JSON.stringify(currentRecipients) !== JSON.stringify(previousRecipients)) {
      console.log("收件人已变更:", currentRecipients);
      previousRecipients = [...currentRecipients];
      // 执行你的业务逻辑
    }
  });

  // 监听容器的子元素变化和内容修改
  observer.observe(toContainer, {
    childList: true,
    subtree: true,
    characterData: true
  });
}

// 启动监听
observeRecipients();

注意:不同网页邮件的DOM结构差异很大,需要针对目标平台调整选择器(比如Outlook网页版的收件人容器类名不同),必要时可以用document.querySelectorAll匹配多个可能的选择器。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 05:39:53