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

Google Apps Script实现Google Form同步Contacts时报TypeError求解

Google表单提交同步到联系人报错排查方案

错误原因

TypeError: Cannot read property 'First name' of undefined报错的核心是addContact函数被调用时,传入的info参数为未定义状态,并非字段引用规则错误。

排查修复步骤

  • 第一步:先测试字段取值是否正确,新增测试函数直接读取表格数据验证:
function testContactField() {
  // 替换为你实际存储表单响应的工作表名称
  const responseSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("表单响应 1");
  // 读取表头和最新一行提交数据
  const headers = responseSheet.getRange(1, 1, 1, responseSheet.getLastColumn()).getValues()[0];
  const latestRow = responseSheet.getRange(responseSheet.getLastRow(), 1, 1, responseSheet.getLastColumn()).getValues()[0];
  // 组装info对象
  const testInfo = {};
  headers.forEach((header, idx) => {
    testInfo[header] = latestRow[idx];
  });
  // 执行后在脚本编辑器「执行记录-日志」中查看输出结果
  console.log("完整info对象:", testInfo);
  console.log("First name取值:", testInfo['First name']);
  // 测试调用原函数
  addContact(testInfo);
}
  • 第二步:修正表单触发逻辑
    Google表单提交的可安装触发器,默认传递的是事件对象e,不会自动组装成你需要的info结构,需要你手动提取数据,触发器需要绑定如下函数,不要直接绑定addContact:
function onFormSubmitHandler(e) {
  const contactInfo = {
    "First name": e.namedValues["First name"][0],
    "Last name": e.namedValues["Last name"][0],
    "Email": e.namedValues["Email"][0]
  };
  addContact(contactInfo);
}
  • 第三步:给原函数加参数校验避免报错
function addContact(info) {
  // 前置校验,参数缺失直接返回并打印日志
  if(!info || !info['First name'] || !info['Last name'] || !info['Email']) {
    console.error("联系人参数不完整,跳过执行:", info);
    return;
  }
  const c = ContactsApp.createContact(info['First name'], info['Last name'], info['Email']);
  const cg = ContactsApp.getContactGroups();
  // 建议不要用索引取分组,避免分组顺序变化报错,改用名称匹配
  const targetGroup = cg.find(group => group.getName() === "你要添加到的联系分组名称");
  if(targetGroup) {
    c.addToGroup(targetGroup);
  }
}

结果验证

执行testContactField函数后,打开Google Apps Script编辑器左侧的「执行记录」面板,即可查看info对象的完整内容和对应字段的取值,确认引用是否正确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 06:45:03