【问题标题】:Google App Scripts onOpen() trigger doesn't work on sheetsGoogle App Scripts onOpen() 触发器在工作表上不起作用
【发布时间】:2019-01-17 12:35:00
【问题描述】:

我无法在打开电子表格时运行我的脚本。我已经手动设置了触发器see。授权范围也已设置。

该代码旨在从工作表中的表格中获取一些联系信息,创建一个联系人,然后将该联系人添加到表格中指定的电子邮件列表中。有一个功能可以检查此电子邮件是否已存在并防止重复。如果我从脚本编辑器运行代码,它可以正常工作。我不确定为什么我无法使用onOpen(e) 触发器运行它。

我认为该问题与this 有关,但最低限度的代码对我有用,并在打开的触发器上创建了第二张工作表。

感谢任何帮助,因为我很困惑 - 它一定与我的代码有关。

代码:

function onOpen(e) {
  var sheet = SpreadsheetApp.getActiveSheet();
  var dataRange = sheet.getDataRange();
  var data = dataRange.getValues();
  

  // Iterate through all the data minus the header
  for (var i=1; i<data.length; i++){
    currApplicant = data[i]
    applicantFirstName = currApplicant[1]
    applicantLastName = currApplicant[2]
    applicantEmail = currApplicant[3]
    emailGroup = currApplicant[13]
    addToEmailBool = currApplicant[12]    //do you want to add them to the email list?
    var numDuplicates = 0;

    Logger.log(applicantEmail); 

    if ((addToEmailBool == 1) && (emailGroup != "")) {
        var duplicateCounter = 0; 
        var numDuplicates = checkForDuplicates(emailGroup, applicantEmail);
      
      if (numDuplicates==0){
        var contact = ContactsApp.createContact(applicantFirstName, applicantLastName, applicantEmail);
        var members = ContactsApp.getContactGroup(emailGroup);
        members.addContact(contact);
        Logger.log("Adding:", applicantEmail)
        Browser.msgBox("Added new contact");
      }
    }
  }
  
}

function checkForDuplicates(emailGroup, applicantEmail) { 
  var duplicateCounter = 0; 
  var groupContacts = ContactsApp.getContactGroup(emailGroup).getContacts()
  
  //go thru all the contacts in this group and check if their emails == applicantEmail
  for (var i in groupContacts) {
    var emails = groupContacts[i].getEmails();   
    for (var e in emails) {
      if (emails[e].getAddress() == applicantEmail){
        duplicateCounter += 1;
        Logger.log("Duplicate found:", applicantEmail);       
      }
    }
  }
  return duplicateCounter;
}

【问题讨论】:

  • 您应该真正使用var 来声明变量以确保它们具有本地范围。
  • python 的坏习惯!会记住这一点:)

标签: javascript google-apps-script google-sheets


【解决方案1】:

简单触发器不能用于需要授权的进程。

进一步阅读文档状态:

G Suite application triggers

G Suite 应用程序的可安装触发器在概念上类似于 onOpen() 等简单触发器,但它们可以响应其他事件,并且行为不同。

例如,只要具有编辑权限的用户打开电子表格,Google 表格的可安装打开触发器就会激活,就像简单的 onOpen() 触发器一样。 但是,可安装版本可以调用需要授权的服务。 可安装版本在创建触发器的用户的授权下运行,即使其他具有编辑权限的用户打开电子表格也是如此。

【讨论】:

  • 哦,错过了@Cooper 的那个细节!有什么办法我仍然可以完成这项任务吗? Woukd an editor-add on be my go to?
  • 阅读我添加到答案中的附加说明。现实情况是,您应该始终返回文档,因为它处于不断变化的状态。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多