Reputation: 962
I have the following google apps script that populates an array based on values of a google-sheet as well as creates a web-app. The top section of my code has been tested and works fine.
function doGet() {
return HtmlService.createHtmlOutputFromFile('FormFile')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function ChannelList() {
var InfoSheetIterator = DriveApp.getFilesByName("InfoSheets");
var InfoSheetFile = InfoSheetIterator.next();
var InfoSheet = SpreadsheetApp.open(InfoSheetFile);
var NumChannels = getLastRow('A');
var ChannelTwoDimArray = InfoSheet.getRange('A2:A'+String(NumChannels)).getValues();
return ChannelTwoDimArray;
}
Then I am in the process of trying to declare an array as a global variable in Javascript and then use that array for other purposes further down the road with this code. I am getting an empty array and I am not sure why. Any tips appreciated.
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<button type="button" onclick="tester()">Click Me!</button>
<p id = "tester"></p>
<script>
//declaring global variables
window.onload = populateArrays;
function getChannelList(value) {
window.ChannelList = value;
}
function populateArrays() {
google.script.run.withSuccessHandler(getChannelList).ChannelList();
}
function tester() {
document.getElementById("demo").innerHTML = window.ChannelList[0][0];
}
</script>
</body>
</html>
Edit: Things I have tried:
- Adding multiple script tags.
- setting a timeout to the printing of ChannelList values.
- global variables
- local storage window variables
I am missing something here. When I print the values of ChannelList in the getChannelList() method it works fine, but when I try to access its values outside of that scope... no such luck.
Upvotes: 1
Views: 444
Reputation: 31300
Add a window.onload
event and a success handler
<script>
window.getChannelList = function(rtrnValue) {//Runs AFTER the server function completes
//ToDo - Process the return value
}
window.onload = function() {
google.script.run
.withSuccessHandler(getChannelList)//define the function to run on completion
.ChannelList();//Call the server function
console.log(window.ChannelList[0][0]);
};
</script>
Upvotes: 1