Search code examples
javascriptgoogle-apps-scripttriggersjavascript-objectsrhino

Apps Script get trigger event type name - How to get the name of the event type from the Trigger Class


The following code fails to find the event type of the trigger, even when the event type name as a string is correct. The method getEventType() is getting an object, not a string. According to the documentation at:

https://developers.google.com/apps-script/reference/script/event-type?hl=en

the getEventType() method returns an EventType ENUM. But the documentation does not list any methods to get anything out of the ENUM, and the properties listed in the documentation do not return anything.

Assuming that the event type to find is ON_FORM_SUBMIT how does the code need to be modified to detect whether the trigger is for that event type?

function getEventTypeNameOfTrigger() {
  
  var oneTrigger,triggers,triggerEventType;

  triggers = ScriptApp.getProjectTriggers();//Get the projects triggers
  
  oneTrigger = triggers[0];//Get the first trigger - For testing
  
  triggerEventType = oneTrigger.getEventType();//Use the getEventType method to get the EventType ENUM
  
  Logger.log('triggerEventType: ' + triggerEventType);//Displays the event type name in the logs
  
  Logger.log('typeof triggerEventType: ' + typeof triggerEventType);//Displays "object"
  
  Logger.log(triggerEventType === 'ON_FORM_SUBMIT');//Evaluates to FALSE even when the event type name is ON_FORM_SUBMIT
  
  
}

Solution

  • One possibility is to simply rely on the string representation. Since we know that the event type displays as ON_FORM_SUBMIT when viewing the logs, we know that calling toString() on the eventType will correspond to ON_FORM_SUBMIT:

    Logger.log(triggerEventType.toString() === 'ON_FORM_SUBMIT'); // true
    

    The preferred method is to compare the enums:

    switch (triggerEventType) {
      case ScriptApp.EventType.CLOCK:
        Logger.log('got a clock event');
        break;
      case ScriptApp.EventType.ON_FORM_SUBMIT:
        Logger.log('got a form submit event')
        break;
      ...
    }
    

    This is preferred since it means you are not sensitive to how Google implements the enums.