Search code examples
emailgoogle-apps-scriptgoogle-sheetstriggers

onOpen running outside of the sheet being opened


Using Apps Script, I have an email compiler tool built where you select a record, then hit "send email" from a custom ui. It then pulls a popup with a text field for you to enter the email recipient. But that address prompt comes up on opening the sheet on it's own.

Also any additional functions I try to run from the editor are causing that address prompt to pop up. My onOpen is pretty simple:

function onOpen() {
 
 let ui = SpreadsheetApp.getUi(); // Same variations.
    ui.createMenu('Email Tools')
      .addItem('Compile Email','emailSend')
      .addToUi();

}

The only thing I can think of is in the emailSend function, it calls the onOpen() as well. If it doesn't, the UI for the "Email Tools" doesn't load. Now I'm at a loss for how to untangle this.

onOpen();
var emailTo = addressPrompts();
function emailSend(emailTo) {
  let toField = PropertiesService.getScriptProperties().getProperty('to');
  let ccField = PropertiesService.getScriptProperties().getProperty('cc');

I've tried modifying the trigger for the addressPrompt() function because it is currently set up to run onOpen. That didn't seem to help.

If I disable the onOpen() from the emailSend function, then the menu doesn't load to the spreadsheet at all.


Solution

  • You shouldn't have the line:

    onOpen();
    

    within your script. The onOpen(); calls the ui function and causes you the problem.

    Google Apps Script only needs the definition of the function function onOpen() {...}.