I have a Google Docs sidebar that has text input and a search button. After entering a name, the search button will pull data from a Sheets database, and I want it to be able to populate a text display.
For example, right now, I have it simply displayed using paragraphs. "Source goes here" would be replaced with the variable data from Google Apps Script.
<p>
<b>Source:</b> Sources goes here<br>
</p>
I've seen snippets that talk about using something like:
var html = HtmlService.createHtmlOutputFromFile('ToolPage');
var demoValue = "testValue";
html.demoVariable = demoValue;
Which would then use html:
<p>
<b>Source:</b> <span id=demoVariable></span><br>
</p>
But, I don't get any output. Have I misunderstood something fundamental? Or am I at least on the right track?
CodePudding user response:
To dynamically update text in an HTML page using data from Google Apps Script (GAS), you can use the google.script.run API to call a GAS function that retrieves the data and then use the innerHTML property of a DOM element to set the text of that element to the retrieved data. Here is an example of how this might work:
In the HTML page, add a DOM element that will contain the dynamically updated text.
<p id="dynamicText">Loading...</p>
In the GAS code, create a function that retrieves the data you want to display in the HTML page. For example, if the data is stored in a Google Sheets spreadsheet, you can use the Sheets API to read the data from the spreadsheet and return it as an array of values.
function getData() {
// Get the data from the spreadsheet
var ss = SpreadsheetApp.openById('SPREADSHEET_ID');
var sheet = ss.getSheetByName('Sheet1');
var data = sheet.getDataRange().getValues();
// Return the data as an array of values
return data;
}
In the JavaScript code that runs on the HTML page, use the google.script.run API to call the GAS function and retrieve the data. Then, use the innerHTML property of the DOM element to set the text of that element to the retrieved data.
// Get the DOM element that will contain the dynamic text
const dynamicText = document.getElementById('dynamicText');
// Call the GAS function to get the data
google.script.run
.withSuccessHandler(data => {
// Set the text of the DOM element to the retrieved data
dynamicText.innerHTML = data.join(', ');
})
.getData();
In this example, the getData() function is called using the google.script.run API, and the retrieved data is passed to the success handler function as an array of values. The success handler function then sets the text of the dynamicText element to the retrieved data, using the innerHTML property.
You can adjust the code to fit your specific needs, such as using a different data source or formatting the data in a different way. Additionally, you can use additional methods of the google.script.run API, such as withFailureHandler(), to handle errors and other situations.