NikitOn
NikitOn

Reputation: 468

How to identify whether Google Apps Script is launched as a Trigger or Manually?

How can I identify in Google Apps Script whether the script itself was triggered by some event or it was launched by someone?

Upvotes: 4

Views: 1118

Answers (4)

Wicket
Wicket

Reputation: 38130

Functions triggered by an event like on-open or by time events will get an event object. There are a few properties that are common for all event objects that always get a value: authMode and triggerUid. You might check if the event object has values for these properties.

Considering that arguments can be used to refer to a function's arguments, a general way to check if a trigger called the function is the following:

function myFunction(){
  if(arguments[0] && arguments[0].authMode){
    Logger.log('myFunction was called by a trigger');
  } else {
    Logger.log(('myFunction was NOT called by a trigger');
  }
}

Upvotes: 0

Justin Poehnelt
Justin Poehnelt

Reputation: 3459

With code similar to:

let TRIGGERED = undefined;

function main(e) {
  console.log(e);

  if (e) {
    TRIGGERED = true;
  }
}

When using an installable time-based trigger, I get the following for e. Simple triggers will also have e defined:

{ year: 2024,
  'day-of-week': 2,
  second: 40,
  authMode: ScriptApp.AuthMode.FULL, // https://developers.google.com/apps-script/reference/script/auth-mode
  minute: 38,
  'day-of-month': 26,
  hour: 22,
  triggerUid: '470041830',
  timezone: 'UTC',
  month: 11,
  'week-of-year': 48 
}

Upvotes: 0

Vytautas
Vytautas

Reputation: 2286

Technically that is possible. If you are using simple triggers you must not call the function from another function. In that case you simply use your function as let's say onEdit(e) and try to check the values of e. For example check what is the value of e.source. Simple triggers will generaly have that value. Review this page to see what event handlers you can look for.

With installable triggers it's easier. Let's say you have function1(e) which you set up a trigger for. You can now check if you have a value for e.triggerUid. You can also use that value to delete the trigger if you want!

Upvotes: 5

Sujay Phadke
Sujay Phadke

Reputation: 2196

I don't think there's a way for the script to know that. The simple triggers you can use are listed here: GAS-triggers. But it's also possible to invoke those functions manually through the GAS editor GUI or a menu item which calls the function.

Upvotes: -3

Related Questions