¿Puedo usar la barra lateral de HTML para llamar una función en Google Appscript?
Necesito usar una barra lateral para obtener algunas variables e imprimirlas en la última línea de una hoja, usando AppScript. Así que intenté usar este código:
Sidebar.HTML
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<p>Name: <input type="text" name="txtName"></p>
<p>Date: <input type="text" name="txtDate"></p>
<p>Value: <input type="text" name="txtValue"></p>
<button onclick="doSomething()"> submit </button>
<script>
function doSomething() {
google.script.run.withFailureHandler(myFunction(document.getElementById("txtName").value,
document.getElementById("txtDate").value,
document.getElementById("txtValue").value))
}
</script>
</body>
</html>
Code.js
function myFunction(name = "", date = "", value = "") {
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName("1");
var lr = sheet.getLastRow() + 1;
sheet.getRange(lr, 1).setValue(name);
sheet.getRange(lr, 2).setValue(date);
sheet.getRange(lr, 3).setValue(value);
}
function openDialog() {
var html = HtmlService.createHtmlOutputFromFile("Sidebar");
html.setTitle("Form");
SpreadsheetApp.getUi().showSidebar(html);
}
Pero no funcionó. Cuando hago clic en el botón no sucede nada. Soy nuevo en HTML, ¿qué puedo hacer para solucionarlo?
davy.ai
Para solucionar el código, se deben realizar algunos cambios.
Sidebar.HTML
– En la función
doSomething()
, se debe cambiargoogle.script.run.withFailureHandler()
porgoogle.script.run.withSuccessHandler()
.– Se debe cambiar
myFunction(document.getElementById("txtName", "txtDate", "txtValue").value)
pormyFunction(document.getElementsByName("txtName")[0].value, document.getElementsByName("txtDate")[0].value, document.getElementsByName("txtValue")[0].value)
para obtener los valores de los campos de entrada.Code.js
–
lr
debería declararse como una variable let o const.– La función
openDialog()
debería modificarse para agregar un elemento de menú o botón a la hoja de cálculo para ejecutar la función. El métodoshowSidebar()
solo puede ser llamado por una acción del usuario, como hacer clic en un botón o elemento de menú.Aquí está el código corregido:
Sidebar.HTML
Code.js
La función
onOpen()
agrega un elemento de menú a la hoja de cálculo que ejecuta la funciónopenDialog()
para mostrar la barra lateral.