Google Apps脚本 - 移动光标点击

时间:2015-10-16 07:45:14

标签: javascript html google-apps-script google-docs

我想在Google文档文档的侧边栏中实现目录,该文档会在您点击时将您带到相应的部分。我正在按元素生成侧边栏元素的HTML,我看到moveCursor(position)类中有Document函数,但我无法看到如何使用onclick实际调用它。不是完整的代码,但显示了问题:

function generateHtml() {
  var html = HtmlService.createHtmlOutput('<html><body>');
  var document = DocumentApp.getActiveDocument();
  var body = document.getBody();

  //Iterate each document element
  var totalElements = body.getNumChildren();
  for(var i = 0; i < totalElements; ++i) {
    var element = body.getChild(i);

    if(element.getType() == DocumentApp.ElementType.PARAGRAPH) {
      var text = paragraph.getText();

      if(text.trim()) { //Not blank paragraph
        var position = document.newPosition(element, 0);

        /**Would like to have <a onclick=document.moveCursor(position)> here**/

        //Show first 20 chars as preview in table of contents
        html.append('Detected paragraph ')
        .append(text.substring(0, 20))
        .append('<br />');
      }
    }
  }

  html.append('</body></html>');
  return html;
}

如何在Apps脚本中完成此操作?代码可以根据需要进行完全重构。

1 个答案:

答案 0 :(得分:0)

这一行:

/**Would like to have <a onclick=document.moveCursor(position)> here**/

更改为:

<div onmouseup="myClientFunction()">Text Here</div>

在HTML中添加<script>标记:

<script>
  var valueToSend = code to get value;

  window.myClientFunction = function() {
    google.script.run
      .myGsFunctionToMoveCursor(valueToSend);
  };
</script>

然后在脚本文件(.gs扩展名)中需要myGsFunctionToMoveCursor()函数

function myGsFunctionToMoveCursor(valueReceived) {
  //To Do - Write code to move cursor in Google Doc
  . . . Code to move cursor
};