Piotr
Piotr

Reputation: 13

Adding a time based trigger using an add-on throws an error that does not exist when running the same code in the editor

I have included the code below. The issue is that when the 'createTestTrigger' function is run from the editor the function runs, creates the trigger, and the trigger runs. However, when I "Test as add-on" with a spreadsheet and run it from the add-on menu it fails with the following error:

Unexpected error while getting the method or property create on object ScriptApp.ClockTriggerBuilder.

This only seems to fail when running as an add-on. I tested it as part of a project in a workbook and that worked fine as well. I cannot find any documentation that would confirm my suspicions that Google simply does not allow add-ons to create triggers but I cannot find anything.

function onOpen(e) {
  const ui = SpreadsheetApp.getUi();
  var menu = ui.createAddonMenu();
  menu.addItem('Test trigger creattion', 'createTestTrigger')
  menu.addToUi();
}

function createTestTrigger() {
  ScriptApp.newTrigger('toBeTriggered')
  .timeBased()
  .after(5000)
  .create();
}

function toBeTriggered(e) {
  Logger.log('Ran from trigger: ' + e.triggerUid);
}

Upvotes: 1

Views: 215

Answers (1)

Alan Wells
Alan Wells

Reputation: 31300

Quote from Google documentation:

Installable triggers aren't supported when testing. Functionality that depends on installable triggers are not testable.

https://developers.google.com/gsuite/add-ons/how-tos/testing-editor-addons#testing_details

You can not install a time based trigger when using the "Run - Test as add-on" menu item.

The best way to develop your add-on is by creating a bound script to the document, and running it that way. For example, if it's a Sheets add-on, from the Sheets menu, click "Tools - Script editor" and a new Apps Script project will open and automatically be bound to the spreadsheet.

The problem with developing an add-on from a bound script, is that if you want to publish your add-on from a stand-alone script, then you need a way to transfer all the files from the bound project to the stand-alone project. You won't want to manually copy and paste files. One way to do that is with the Chrome extension:

https://chrome.google.com/webstore/detail/google-apps-script-github/lfjcgcmkmjjlieihflfhjopckgpelofo?hl=en

Upload to GitHub from the bound project then download from GitHub to the stand-alone project.

Related Note: A time trigger created by an add-on can only run once per hour at most: https://developers.google.com/apps-script/guides/triggers/installable#time-driven_triggers

An add-on can not install one time-based trigger, and then 10 minutes later delete the first trigger and then install another time-based trigger.

Upvotes: 1

Related Questions