调用ContactsApp.createContact参数不匹配及手机号未同步问题咨询
问题原因
ContactsApp.createContact 原生仅支持3个入参,顺序为「名、姓、邮箱」,你传入了4个参数(额外加了手机号),不符合方法签名要求,因此触发参数不匹配报错。手机号无法通过该方法直接传入,需要在联系人创建完成后单独调用接口添加。
同时你定义的表单提交触发器函数formSubmitted会给addContact传入事件参数e.namedValues,但现有addContact没有定义参数接收,会导致触发器触发时取值异常。
修正后的完整代码
// 初始化菜单 function onOpen() { var ui = SpreadsheetApp.getUi(); ui.createMenu('联系人工具') .addItem('查看所有联系人群组', 'showContactGroups') .addItem('添加当前行联系人', 'addContact') .addToUi(); } // 表单提交触发入口 function formSubmitted(e) { // 直接取表单提交的字段值,引号内替换为你自己表格对应列的表头名称 var first_name = e.namedValues['名'][0]; var last_name = e.namedValues['姓'][0]; var email = e.namedValues['邮箱'][0]; var phone = e.namedValues['手机号'][0]; saveContact(first_name, last_name, email, phone); } // 手动添加当前行联系人入口 function addContact() { var sheet = SpreadsheetApp.getActiveSheet(); var active_row = sheet.getActiveCell().getRow(); var range = sheet.getDataRange(); var first_name = range.getCell(active_row ,1).getValue(); var last_name = range.getCell(active_row ,2).getValue(); var email = range.getCell(active_row,3).getValue(); var phone = range.getCell(active_row,4).getValue(); saveContact(first_name, last_name, email, phone); } // 通用保存联系人逻辑 function saveContact(first_name, last_name, email, phone) { // 仅传3个符合要求的参数创建联系人 var contact = ContactsApp.createContact(first_name, last_name, email); // 单独添加手机号 if(phone) { contact.addPhone(ContactsApp.Field.MOBILE_PHONE, phone); } // 添加到我的联系人群组 var mainGroup = ContactsApp.getContactGroup("System Group: My Contacts"); mainGroup.addContact(contact); showOutputBox('名:' + first_name + '\n姓:' + last_name + '\n邮箱:' + email + '\n手机号:' + phone, "联系人添加成功"); } // 弹窗输出工具 function showOutputBox(str, title) { var html = HtmlService.createHtmlOutput('<pre>'+str+'</pre>') .setWidth(400) .setHeight(300); SpreadsheetApp.getUi().showModalDialog(html, title); } // 查看所有联系人群组 function showContactGroups() { var groups = ContactsApp.getContactGroups(); var str ='群组列表\n'; for(var g = 0; g < groups.length; g++) { str +='\n'+groups[g].getName() } showOutputBox(str,'你的联系人群组'); }
注意事项
- 表单触发器使用前需要在
formSubmitted函数内把字段名替换为你自己表格对应的表头名称,避免取值错误 - 代码对手机号为空的场景做了兼容,不会触发异常
内容的提问来源于stack exchange,提问作者Fresh Flowers
相关产品推荐
相关产品推荐

