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

如何在Gmail Chrome扩展中触发Google Apps Script?

如何从Gmail Chrome扩展触发Google Apps Script

我来帮你梳理下具体的实现步骤,核心思路是把你的Google Apps Script(GAS)部署为Web App,然后通过Chrome扩展发送HTTP请求来调用它。下面分步骤拆解:

第一步:调整并部署你的GAS为Web App

你的现有脚本是直接操作Gmail收件箱的逻辑,但要被外部调用,需要包装成Web App支持的入口函数(doGet或doPost)。这里我们用doPost来处理POST请求:

function doPost(e) {
  // 执行你原本的Gmail处理逻辑
  var thread = GmailApp.getInboxThreads(0,1)[0];
  var message = thread.getMessages()[0];
  var sub = message.getSubject();
  var body = message.getPlainBody();
  var text = /(Event)|(Party)/;
  let result = sub.match(text);
  if(result == null) {
    result = body.match(text);
  }
  // 这里继续你的labels处理逻辑...
  
  // 返回执行结果给Chrome扩展
  return ContentService.createTextOutput(JSON.stringify({
    result: result,
    subject: sub
  }))
  .setMimeType(ContentService.MimeType.JSON);
}

接下来部署Web App:

  • 打开你的GAS项目,点击右上角「部署」→「新部署」
  • 选择部署类型为「Web应用」
  • 配置权限:
    • 「执行」选择「我」(因为脚本需要访问你的Gmail数据)
    • 「谁可以访问」:如果仅自己使用,选「只有我」;如果要开放给他人,选「任何人,甚至匿名」(注意:开放匿名访问会有安全风险,谨慎选择)
  • 点击部署后,复制生成的Web App URL(比如https://script.google.com/macros/s/xxxxxx/exec),这是扩展调用的核心地址。

第二步:在Chrome扩展中添加触发按钮并调用Web App

1. 配置扩展Manifest

首先在manifest.json中添加必要的权限,允许访问Web App和Gmail页面:

{
  "manifest_version": 3,
  "name": "我的Gmail工具",
  "version": "1.0",
  "permissions": ["activeTab", "scripting"],
  "host_permissions": ["https://script.google.com/macros/s/xxxxxx/exec", "https://mail.google.com/*"],
  "action": {
    "default_popup": "popup.html"
  }
}

替换xxxxxx为你的Web App ID,确保host_permissions包含你的Web App地址和Gmail域名。

2. 制作弹出页面(含触发按钮)

创建popup.html,添加一个触发按钮:

<!DOCTYPE html>
<html>
<head>
  <style>button { padding: 8px 16px; cursor: pointer; }</style>
</head>
<body>
  <button id="runGASBtn">执行Gmail脚本</button>
  <script src="popup.js"></script>
</body>
</html>

3. 编写按钮点击逻辑(调用Web App)

创建popup.js,实现点击按钮后发送请求到Web App:

const WEB_APP_URL = 'https://script.google.com/macros/s/xxxxxx/exec';

document.getElementById('runGASBtn').addEventListener('click', async () => {
  try {
    // 发送POST请求到Web App
    const response = await fetch(WEB_APP_URL, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' }
      // 如果需要给GAS传参数(比如当前邮件ID),可以添加body:
      // body: JSON.stringify({ threadId: 'xxx' })
    });

    if (!response.ok) throw new Error(`请求失败:${response.status}`);
    
    const result = await response.json();
    console.log('脚本执行结果:', result);
    alert(`脚本已执行!匹配结果:${result.result ? result.result[0] : '无匹配'}`);
  } catch (error) {
    console.error('触发脚本出错:', error);
    alert('触发失败,请检查控制台日志');
  }
});

进阶:操作当前打开的Gmail邮件

如果你的脚本需要处理用户当前打开的邮件(而不是收件箱第一封),可以在扩展中获取当前邮件的threadId并传给GAS:

在popup.js中添加获取当前邮件ID的函数:

async function getCurrentThreadId() {
  const [activeTab] = await chrome.tabs.query({ active: true, currentWindow: true });
  const scriptResult = await chrome.scripting.executeScript({
    target: { tabId: activeTab.id },
    func: () => {
      // 从Gmail页面URL中提取threadId
      const urlParams = new URLSearchParams(window.location.search);
      return urlParams.get('threadId');
    }
  });
  return scriptResult[0].result;
}

然后修改点击逻辑,把threadId传给GAS:

document.getElementById('runGASBtn').addEventListener('click', async () => {
  try {
    const threadId = await getCurrentThreadId();
    if (!threadId) {
      alert('请在Gmail邮件页面触发脚本!');
      return;
    }

    const response = await fetch(WEB_APP_URL, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ threadId: threadId })
    });

    // ...后续处理逻辑不变
  } catch (error) {
    // ...错误处理不变
  }
});

同时修改GAS的doPost函数,接收并使用threadId:

function doPost(e) {
  const params = JSON.parse(e.postData.contents);
  const threadId = params.threadId;
  
  // 使用传入的threadId获取邮件线程
  var thread = GmailApp.getThreadById(threadId);
  var message = thread.getMessages()[0];
  
  // ...后续逻辑不变
}

安全注意事项

  • 如果Web App设置为「只有我」访问,需要在扩展中使用Chrome的identity API获取OAuth令牌,在请求头中带上Authorization: Bearer {token}才能通过验证。
  • 避免在扩展中硬编码敏感信息,比如OAuth客户端ID,建议使用Chrome的存储API管理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:18:57