I have a Google Apps Script that adds a side bar to an Sheets file. Before the side bar loads it creates an array of objects. The side bar has next/previous buttons. Then the goal is to show data from each row, one at a time, in the side bar.
function myFunction() {
var ui = SpreadsheetApp.getUi();
var testData = [{"name" : "bob", "age" : 32}, {"name" : "sue", "age" : 31}, {"name" : "dingo", "age" : 7}];
var sideBar = HtmlService.createTemplateFromFile("sideBar");
ui.showSidebar(sideBar.evaluate().setTitle("Selector"));
}
In the above example, testData
is what I want to share with the side bar.
I am trying to figure out the best way to share the array of objects with the sideBar client script.
My first thought was to pass it as a template variable:
sideBar.data = testData;
And then assign it to a variable in sideBar.html
:
var data = <?= data ?>;
But this does not work. It returns the testData
as a string to data
so data
becomes a string of the testData
.
So then I thought I would leave testData
in the server side script and use google.script.run.withSuccessHandler(function).serverSideFunction(...)
in the client side to get data, one row at a time, from testData
on the server side.
The problem is, testData
is a variable in myFunction
which exists after the side bar is created. So when clientSideFunction(...)
runs, the server side won't know what testData
is anymore.
I could make testData
a global variable in the server side script but I am not sure if that is the best approach.
Is there another, better way to do what I am after?
Update
I guess I cannot use a global variables. In myFunction
, if I set a global variable, after myFunction
finishes the variable data is lost. So when google.script.run.withSuccessHandler(function).serverSideFunction(...)
is run, serverSideFunction
runs in a new context so the global variable is gone.
Update 2
For my use-case, think of a sheet with rows and rows of tasks. The user would click a menu item that would check if any tasks need processing. If there are any rows that need processing it would show a side-bar that shows details for each task that needs processing. The side bar would show details for a task with an input box and a submit button. The user enters data in the input box then hits submit. After submission the script will go do things (complex things) and then show details for the next in-scope task.