I'm trying to learn Google Apps Script, and I just did a bit of an experiment with creating two ".gs files" in the same project, each with an onOpen() function.
After saving, closing, and then opening the document, only one of the onOpen() functions ran (the Sidebar.gs file).
Do these need to be included in the same file? Well, I guess I know that it is a work around. I guess my question is WHY?
Project:
Code.gs:
function onOpen() {
DocumentApp.getUi().createMenu("PACKT").addItem("Greeting","greeting").addToUi();
}
function greeting() {
var ui = DocumentApp.getUi();
ui.alert("Greeting", "Hello World!", ui.ButtonSet.OK);
}
Sidebar.js:
function onOpen() {
var htmlOutput = HtmlService.createHtmlOutput('<button onclick="alert(\'Hello World!\');">Click Me</button>').setTitle("My Sidebar");
DocumentApp.getUi().showSidebar(htmlOutput);
}
Thanks!
You should never have two functions with the same name in the same namespace. It simply doesn't make sense: which of them should be executed when functionName()
call happens? (In reality, the function that was last to be defined will be the surviving one; with the rest lost without trace).
In particular, you should not have two onOpen functions within the same project, be it one file or separate (the files share the namespace, meaning that the functions in one file can be called from the other as if they were in the same file).
But your one onOpen() function can simply call whatever functions need to run:
function onOpen() {
doThisThing();
doAnotherThing();
}