UPDATED: This is totally possible. I just was closing the host window before the async method completed. My interpretation was that the running context would persist, even if the UI was closed out. Nope.
I want to confirm whether Apps Script functions in a spreadsheet container-bound project can or cannot be called via google.script.run from within a JavaScript function in an HTML template that was loaded by the HTMLService. My initial findings indicate "not" (see below), but I might be missing something.
The google.script.run call, when made from within the JS function called by the onclick handler, consistently routes to the error handler function, with the following error code: NetworkError: Connection failure due to HTTP 0.
If I call the google.script.run code directly from the onclick handler of a button, it does run. I'd prefer to be able to use it in a function, so that I can build up a set of data to pass into the real method I'm planning for the implementation.
I did review this bug logged with Google, but in this simple test I am not referencing a library.
Here's more detail: - New version of sheet - New Spreadsheet and AS project created with the simplest code to recreate the issue.
I have the following code in an apps script file in the container-bound project:
function onOpen()
{
var testMenu = SpreadsheetApp.getUi()
.createMenu('Custom Menu');
testMenu.addItem('Show UI in sidebar', 'showSidebar');
testMenu.addToUi();
};
function showSidebar(){
var html = HtmlService.createTemplateFromFile('simpleDialog');
SpreadsheetApp.getUi().showSidebar(html.evaluate());
}
function doWorkInAppsScriptFile()
{
Logger.log("doWorkInAppsScriptFile called.");
}
In the "simpleDialog" html file, which is also in the Apps Script project, I have the following test code:
<h2>google script run test</h2>
<div style="width:98%;margin:10px">
<div style="width:98%;margin:10px;padding:10px;text-align:center">
<input type="button" id="saveButton" onclick="onSave()" value="Save" style="background:DarkGreen;color:White;font-weight:bold;margin:10px"/>
</div>
</div>
<script type="text/javascript">
function onSave(){
google.script.run.withFailureHandler(onFailure).doWorkInAppsScriptFile();
//Moving the following line to an onSuccess handler, and calling .withSuccessHandler,
// allows the code to close the window appropriately. Leaving this in causes the error discussed in this q.
google.script.host.close();
}
function onFailure(error)
{
alert("onFailure: " + error);
}
</script>