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

如何在Chrome扩展中通过POST请求向Google Apps Script传参

解决POST传递JSON参数到Google Apps Script的问题

1. 修改Chrome扩展的fetch请求代码

把要发送的id参数放到body里,并用JSON.stringify()转换成JSON字符串(匹配你设置的Content-Type: application/json):

const url = 'https://script.google.com/.../exec';

fetch(url, {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ id: '123' }) // 这里放入要传递的变量
})
.then(response => response.text())
.then(data => { console.log(data) }); // 会输出 {"id":"123"}

2. 修改Google Apps Script的doPost函数

原来的e.parameter仅支持解析表单编码(application/x-www-form-urlencoded)的请求体,对于JSON格式的请求,需要从e.postData.contents读取原始内容并解析:

function doPost(e) {
  if (typeof e !== 'undefined') {
    // 解析POST过来的JSON数据
    const payload = JSON.parse(e.postData.contents);
    return ContentService.createTextOutput(JSON.stringify(payload));
  }
}

可选:兼容多种请求格式

如果需要同时支持表单编码和JSON格式的请求,可以添加格式判断:

function doPost(e) {
  if (typeof e !== 'undefined') {
    let payload;
    // 根据请求头判断数据格式
    if (e.postData.type === 'application/json') {
      payload = JSON.parse(e.postData.contents);
    } else {
      payload = e.parameter;
    }
    return ContentService.createTextOutput(JSON.stringify(payload));
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 10:40:41