Search code examples
javascriptgoogle-apps-scriptiife

"Script function not found" - Google App Scripts


I'm starting to use Google App Scripts, and with the little I know of JavaScript I tried the following below. I get an error, but the script does seem to be working.

Why does it give an error? It seems that it is specifically looking to run a function when I press the little play button.. Would it be bad practice to structure a google app scripts doc as I have done below?

(function (id) {

  var sheet = SpreadsheetApp.openById(id).getSheets()[0];

  var data = sheet.getDataRange().getValues();

  Logger.log(data);

  sheet.appendRow(['this','is','another', 'bigger','test','of','stuff']);

})('1BXDicksYS19jre0tZKHEjqqyvdzbhbtFfSm053q2sZ0')

=== EDIT ===

Google Apps Scripts shouldn't be run from an IIFE, since it wants to explicityly trigger a function. So yes. I think, in my still limited experience a year later, that this would be a poor way to write a Google Apps Script.


Solution

  • Google App Scripts files ending with a .gs do not run all functions in the file like in JavaScript when you load the file all the IIFE's will run.

    In order to run a function in a .gs file which is what you are using above you need to either add a trigger onOpen or onEdit of the spreadsheet. on open/on edit: https://developers.google.com/apps-script/guides/triggers/

    A time trigger which you can set based on a certain h/d/m condition. installable triggers: https://developers.google.com/apps-script/guides/triggers/installable

    If you want to connect this to a google web app you need to use google.scripts.run.functionName() running .gs function on the client side: https://developers.google.com/apps-script/guides/html/reference/run

    Do not use immediately invoked functions in .gs files. It's also good to have very specific names for your .gs functions because of how the Google App Script file tree works.

    All the functions are accessible in any file within the google app script file tree meaning you can call any function in any file within the google app script.

    Having a function without a name in this structure would make it impossible to call the nameless function. Hope that helps.