Google Workspace Editor Add-on: Trigger Conflict between Workbooks - Code Included, Seeking Solutions

64 Views Asked by At

I have encountered an issue with my Google Workspace Editor add-on. When a user creates a trigger in one workbook, another workbook's trigger stops working. Here's the code for reference. Any help would be highly appreciated.

function createTimeTrigger(triggerTime) {
    const documentProperties = PropertiesService.getDocumentProperties();
    const selectedTriggerTime = documentProperties.getProperty("triggerTime");

    const triggers = ScriptApp.getProjectTriggers();
    triggers.forEach(trigger => ScriptApp.deleteTrigger(trigger));

    let triggerStatus = "";

    if (documentProperties.getProperty("onChangeTrigger") === "true") {
      ScriptApp.newTrigger("testTrigger").forSpreadsheet(SpreadsheetApp.getActive()).onChange().create();
      triggerStatus += " to run on change and on edit.";
    }

    else if (documentProperties.getProperty("onFormSubmitTrigger") === "true" && SpreadsheetApp.getActive().getFormUrl() !== null) {
      ScriptApp.newTrigger("testTrigger").forSpreadsheet(SpreadsheetApp.getActive()).onFormSubmit().create();
      triggerStatus += " to run on form submit.";
    } else if (documentProperties.getProperty("onFormSubmitTrigger") === "true") {
      showAlert_("Error", "Invalid trigger configuration. Form not found.");
      return;
    }

    else if (selectedTriggerTime !== "Select" && selectedTriggerTime !== null) {
      const installableTrigger = ScriptApp.newTrigger("testTrigger").timeBased().everyHours(triggerTime).create();
      triggerStatus += ` to run every ${triggerTime} hour(s).`;
    }

    else if (documentProperties.getProperty("onChangeTrigger") === "true" && selectedTriggerTime !== "Select" && selectedTriggerTime !== null) {
      triggerStatus += ` to run on change, on edit and to run every ${triggerTime} hour(s)`;
    }

    triggerStatus = triggerStatus || "- Triggers are not active.";
    documentProperties.setProperty("triggerStatus", `The schedule has been updated by ${Session.getEffectiveUser().getEmail()} at ${new Date().toLocaleString()}${triggerStatus}`);
    showToast_("Trigger set up successfully.", "");
    getLastRunStatus();
    getTriggerStatus();
    launchApp();
  }
1

There are 1 best solutions below

1
Cooper On

This line is deleting all of the other triggers const triggers = ScriptApp.getProjectTriggers(); triggers.forEach(trigger => ScriptApp.deleteTrigger(trigger)); you don't have to do that all you really need to do is to make sure that there are no other triggers that have the same trigger handler function