Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

130
Vistas
Leer mensaje de la aplicación web

Estoy trabajando en un complemento de aplicación web en Hojas de cálculo de Google. A continuación se muestra el script Addon y webapp. Quiero leer el mensaje de validación/error de la aplicación web y mostrarlo al usuario. Enviaré un mensaje desde doPost (e) como "Verificar valores" y el usuario debería recibir esto como cuadro de mensaje.

 function copyData() { var ss_id = SpreadsheetApp.getActive().getId(); //This is the Web App URL. var url = "https://script.google.com/macros/s/<id>/exec"; var payload = { "ss_id" : ss_id, // Modified } var options = { "method" : "POST", "payload" : payload, "followRedirects" : true, "muteHttpExceptions" : true, }; var result = UrlFetchApp.fetch(url, options); }
 function doPost(e) { var ss_id = e.parameter.ss_id; // Modified var response = { "status" : "FAILED", "ss_id" : ss_id, }; //var ss_id = ss_id[0]; //Use your spreadsheetID to get Output Sheet var Manager_SS=SpreadsheetApp.openById('<id>'); var Manager_Sheet=Manager_SS.getSheetByName('Consolidated_Data'); var FrontDesk_ss = SpreadsheetApp.openById(ss_id); var FrontDesk_sheet = FrontDesk_ss.getSheetByName('Data'); //Get front desk data var sData = FrontDesk_sheet.getRange("A2:C10").getValues(); //Copy data from Front Desk to Manager Sheet. Manager_Sheet.getRange("A2:C10").clear(); Manager_Sheet.getRange("A2:C10").setValues(sData); //Update done after copying data. FrontDesk_sheet.getRange('D1:D10').setValue('Done'); var response = { "status" : "SUCCESS", "sData" : sData, }; return ContentService.createTextOutput(JSON.stringify(response)); }
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Para este ejemplo, estoy usando un script acotado , pero debería ser el mismo para un complemento de editor.

En la hoja de cálculo que queremos validar, creamos un menú personalizado para llamar a una función que realiza una solicitud POST a nuestra aplicación web. Dependiendo de la respuesta, mostramos un contenido u otro.

 const UI = SpreadsheetApp.getUi() const onOpen = () => { /* Adds the custom menu */ UI.createMenu('Custom Function').addItem('Is Valid?', 'checkValidity').addToUi() } const checkValidity = () => { const res = UrlFetchApp.fetch ( /* Change it for your URL */ "https://script.google.com/macros/s/<ID>/exec", { "method": "post", "contentType": "application/json", /* In this example I only send the ID of the Spreadsheet */ "payload": JSON.stringify( { "ss_id": SpreadsheetApp.getActiveSpreadsheet().getId() } ) } ) /* Depending on the response from the Web App */ /* We show different messages */ const { MSG } = JSON.parse(res.getContentText()) UI.alert(MSG === "OK" ? "IS VALID" : "IS NOT VALID") }

Después creamos una Web App que valida el DNI. En este ejemplo, solo estoy validando que la identificación esté contenida en una matriz de identificaciones válidas, pero esto debe reemplazarse por lo que necesite. Como respuesta, solo envío un simple "OK" o "NO OK", pero esto se puede reemplazar con cualquier tipo de información.

 const doPost = (e) => { /* We perform the checks we need */ /* In this example only checking if the id is contained in an array */ /* This should be changed to perform the desired checks */ const validID = ["<VALID_ID_1>","<VALID_ID_2>"] const { ss_id } = JSON.parse(e.postData.contents) /* SpreadsheetApp.openById(ss_id).copy("my_new_copy") */ const checker = validID.includes(ss_id) /* We send back the response */ /* Depending on the checker value */ return ContentService.createTextOutput(JSON.stringify( { "MSG": checker ? "OK" : "NOT OK" } )).setMimeType(ContentService.MimeType.JSON) }
about 4 years ago · Juan Pablo Isaza Denunciar

0

Error de validación de lectura de Webapp

html:

 <!DOCTYPE html> <html> <head> <base target="_top"> </head> <body> <form> <input type="text" id="txt1" name="id" placeholder="Enter Numbers only"/> <input type="button" value="submit" onClick="processForm(this.parentNode);" /> </form> <script> function processForm(obj) { console.log(obj.id.value); if(obj.id.value.match(/[A-Za-z]/)) { google.script.run.displayError("Invalid Characters Found in id field"); } else { google.script.run.sendData(obj); } } </script> </body> </html>

SG:

 function doPost(e) { Logger.log(e.postData.contents); Logger.log(e.postData.type); const ss = SpreadsheetApp.getActive(); const sh = ss.getSheetByName("Sheet1"); let data = JSON.parse(e.postData.contents); let row = []; Object.keys(data).forEach(k => row.push(data[k])); Logger.log(JSON.stringify(row)) sh.appendRow(row); } function sendData(obj) { const url = ScriptApp.getService().getUrl(); const params={"contentType":"application/json","payload":JSON.stringify(obj),"muteHttpExceptions":true,"method":"post","headers": {"Authorization": "Bearer " + ScriptApp.getOAuthToken()}}; UrlFetchApp.fetch(url,params); } function displayError(msg) { SpreadsheetApp.getUi().alert(msg); } function launchMyDialog() { SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutputFromFile('ah1'),'My Dialog'); }
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda