2

I am trying to simply get a button on a sidebar calling a function living in my Code.gs file. Hopefully I am just doing something stupid but here is the situation.

Here is my Code.gs:

function onOpen() 
{
   var testMenu = SpreadsheetApp.getUi() 
      .createMenu('Custom Menu');

      testMenu.addItem('Show UI in sidebar', 'showSidebar');
      testMenu.addToUi();
};

function showSidebar(){
  var html = HtmlService.createTemplateFromFile('Page');
  SpreadsheetApp.getUi().showSidebar(html.evaluate());
}

function doWorkInAppsScriptFile()
{
    var foo = 'bar';
}

And my Page.html:

<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.doWorkInAppsScriptFile();     

}

</script>

With this code I pull up the sidebar in the spreadsheet and click the button. Then when I go to executions in the project editor it shows an execution of the function doWorkInAppsScriptFile but says that it failed. As far as I can tell it doesn't give me any log output for it, but I could be looking in the wrong spot. I thought maybe I had some code in the function that I didn't fully understand so I switched it to just setting a variable, but it still fails every time.

The fact that it shows an execution makes me think that there is nothing wrong with my Page.html. Does google.scripts.run require a return value?

I have no idea what I'm doing wrong, hoping someone here can point out something obvious.

EDIT: Well, I figured it out. It looks like google scripts are a little screwy when you have multiple accounts logged in with google. When I don't have the user that has permissions for the sheet and project set as the default account in google the script fails.

It seems like in that translation from the sidebar html to the server code it wants to use the default google user for some reason. Anyone experience this before? I will probably open a new question since this seems to be a new question now.

Sean O
  • 177
  • 9

1 Answers1

0

This how I ran it:

function testhtml() {
const html='<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.testoe()}</script>';
SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(html),'test');
}

function testoe() {
  Logger.log('do nothing');
}

Logs: Mar 27, 2021, 12:41:46 PM Info do nothing

Cooper
  • 59,616
  • 6
  • 23
  • 54