传递信息到服务器端的功能在谷歌文档添加

Passing information to server-side function in a Google Docs Add On

本文关键字:谷歌 文档 添加 功能 信息 服务器端      更新时间:2023-09-26

我正在做一个基于Google快速入门教程的Google Docs插件。我正试图改变教程中Add On的工作流程,以添加新页面,然后在新页面上插入翻译,而不是逐行工作流程。

我有一个在单个文档中工作的脚本,但我很难将其移动到Add On架构。我认为这与将选择从客户端JS传递到服务器端脚本进行翻译有关。

这是翻译脚本

function translate(origin, dest, savePrefs) {
  Logger.log('Starting the script');
  if (savePrefs == true) {
    var userProperties = PropertiesService.getUserProperties();
    userProperties.setProperty('originLang', origin);
    userProperties.setProperty('destLang', dest);
    Logger.log(origin,dest);
  }
  var doc = DocumentApp.getActiveDocument();
  var body = doc.getBody();
  // Add a page break for the translated material.
  body.appendPageBreak();
  // Get the number of elements in the document
  var elements = body.getNumChildren();
  Logger.log('Got the page elements');
  // Use the number to loop through each element in the document.
  for( var i=0;i<elements;i++) {
   var element = body.getChild(i).copy();
    var type = element.getType();
    Logger.log('Element Types were successful. Starting tests.');    
    // Test each type for a child element and run script based on the result
    // Images are nested in a paragraph as a child, so the second `if` makes
    // sure there is no image present before moving to the next paragraph.
    if( type == DocumentApp.ElementType.PARAGRAPH ){
      if(element.asParagraph().getNumChildren() != 0 && element.asParagraph().getChild(0).getType() == DocumentApp.ElementType.INLINE_IMAGE) {
        var img = element.asParagraph().getChild(0).asInlineImage().getBlob();
        body.appendImage(img);
      } else if(element.asParagraph().getNumChildren() !=0 && element.asParagraph().getChild(0).getType() == DocumentApp.ElementType.INLINE_DRAWING) {
        var drawing = element.asParagraph().copy();
        body.appendParagraph(drawing);
      } else {
        var text = element.asParagraph().getText();
        Logger.log(text);
        var spn = LanguageApp.translate(text, origin, dest);
        body.appendParagraph(spn);
      }
    } else if(type == DocumentApp.ElementType.TABLE) {
      element.asTable().copy();
      body.appendTable(element);
    } else if(type == DocumentApp.ElementType.LIST_ITEM) {
      var list = element.asListItem().getText();
      body.appendListItem(LanguageApp.translate(list, origin, dest));
    }
  }

客户端JS是:

$(function() {
    $('#run-translation').click(loadPreferences);
    google.script.run(runTranslation)
  });
function runTranslation() {
    this.disabled = true;
    var origin = $('input[name=origin]:checked').val();
    var dest = $('input[name=dest]:checked').val();
    var savePrefs = $('#save-prefs').is(':checked');
    google.script.run
      .runTranslation(origin, dest, savePrefs);
  }

如果我将翻译中使用的语言硬编码到服务器端脚本中,它就可以工作。但是当我尝试使用单选按钮中的变量时,它不会运行。我在控制台中没有看到任何错误,也无法从编辑器中运行脚本来检查日志。我如何调试这段代码?

从客户端Javascript调用服务器端函数

你有一个小的语法错误与google.run:

google.script.run(runTranslation)

应该是:

google.script.run
             .withFailureHander(failFunc) // Optional
             .withSuccessHander(succFunc) // Optional
             .serverFunction(optionalParams...);

两个Handler方法从客户端JavaScript分配回调函数,以便在服务器端函数成功或失败的情况下调用。在这两种情况下,客户端函数都是作为唯一的参数提供的。

您想要与之通信的服务器端函数被表示为好像它本身是一个方法一样,具有可选参数以跨界传递。

最简单的情况是:

google.script.run
             .translate(origin, dest, savePrefs);

(你有runTranslation在你发布的代码,但服务器端功能被命名为translate()…我想这是正确的。)

现在,这个可能不能解决您的所有问题,所以您明智地询问调试…

调试Google Apps Script中的异步客户端/服务器代码

提供的调试环境不足以调试这种客户机/服务器交换。在使用异步执行时,调试器也有弱点——你可以在看不到onEdit触发器的日志中了解更多。

在这种情况下,最简单的调试工具是将日志写入电子表格

/**
 * Write message and timestamp to log spreadsheet.
 * From: https://stackoverflow.com/a/32212124/1677912
 */
function myLog( message ) {
  var ss = SpreadsheetApp.openById( logSpreadsheetId );
  var logSheet = ss.getSheetByName("Log") || ss.insertSheet("Log");
  logSheet.appendRow([ new Date(), message );
}

你可以这样从客户端Javascript调用它:

google.script.run.myLog( "CLIENT: " + message );

这是一个基本的方法,但是您可以通过使用实用函数和BetterLog库来扩展它。在我的博客中可以看到更多的信息,你知道吗?(您可以从客户端JavaScript登录到电子表格!)