google-apps-script:事件触发器上没有 "source" 字段

google-apps-script: No "source" field on event trigger

我已经设置了一个触发器,用于将 Google 表单提交到 运行 我的 Google 脚本之一:

ScriptApp.newTrigger('onFormSubmitted')
    .forForm(form).onFormSubmit().create();

我的 onFormSubmitted 函数被触发,但提供给该函数的事件参数没有 source 属性。它具有 the documentation says it should have.

的 4 个字段中的 3 个

那么我应该如何获取触发此事件的表单的引用?

TMI

function onFormSubmitted(data, arg) {
  log(8, data['triggerUid'], -1) // => 1874727473075378640
  log(9, data['authMode'], -1) // => FULL
  log(10, data['response'], -1) // => FormResponse
  log(11, data['source'], -1) // => undefined
}

documentation for the event object, if the script is not bound, then there is no associated source property. You can overcome this by storing the form id in properties中所述使用触发器uid。然后在您的表单提交代码中,使用触发器 uid 获取正确的表单。

function getFormId_(triggerId) {
  const store = PropertiesService.getScriptProperties();
  var formId = store.getProperty(triggerId);
  if (!formId) console.warn("No form ID found for trigger ID '" + triggerId);
  return formId;
}
function createSubmitTrigger_(form, functionName) {
  const formId = form.getId();
  const trigger = ScriptApp.newTrigger(functionName).forForm(form)
      .onFormSubmit()
      .create();

  const store = PropertiesService.getScriptProperties();
  store.setProperty(trigger.getUniqueId(), formId);
}

function myFormSubmit(e) {
  const form = FormApp.openById(getFormId_(e.triggerUid));
  ...
}

有可能这种方法(存储和检索)可以向后应用,尽管这将取决于之前如何配置触发器 - 您不能以编程方式(或以其他方式)与其他触发器交互。

function storeAll() { // Run once (more is ok too, will just overwrite existing keys).
  function cb(acc, t, i, allVals) { // callback for Array#reduce
    acc[t.getUniqueId()] = t.getTriggerSourceId();
    return acc;
  }

  const newProps = ScriptApp.getProjectTriggers().reduce(cb, {});
  PropertiesService.getScriptProperties().setProperties(newProps);
}

参考资料