将自定义属性添加到Google文档文本

时间:2014-09-25 06:51:09

标签: google-apps-script

我需要创建一个google apps脚本,它会在活动文档中插入一些字符串。 我需要稍后知道用户是否在文档上使用了脚本并更改了已插入的文本。

是否可以为我要添加的字符串标记或插入自定义属性/属性?

例如,而不是添加

<b>Custom Text</b>

可以插入吗?

<p CustomAttribute=Cust1>Custom Text</p>

另外,如何在doc中搜索我的自定义属性?

1 个答案:

答案 0 :(得分:3)

您可以使用NamedRanges实现此类效果。基本上,策略是:

  1. 添加文字,段落或其他文档元素
  2. 在文档NamedRange
  3. 中包装该文本
  4. 记录NamedRange ID,并将其与您需要附加到该特定文本的任何其他数据相关联(例如插入时间或自定义属性等)。
  5. 稍后,当您需要查找该文本(或只是确定它是否存在)时,您可以查询NamedRange ID列表,然后使用该ID引用文档中的文本。
  6. 以下是此类策略的粗略实施:

    function testing() {
      // Add a new paragraph within a Named Range
      var named = addTextWithNamedRange('This is my added text', 'RangeLabel01');
    
      // NamedRanges can share the same names, but the IDs are unique,
      //   so use IDs to easily reference specific NamedRanges  
      var namedId = named.getId();
    
      // Now save this ID to a data structure, along with any other information
      //   about it you need to record
    
      // Later, when you need to reference that text/paragraph/element,
      //   use the ID to find it, and make any changes you need:
      accessNamedRange(namedId);       
    }
    
    function addTextWithNamedRange(str, name) {
       // Add a new paragraph to end of doc
       var doc = DocumentApp.getActiveDocument();
       var body = doc.getBody();
       var text = body.appendParagraph(str); 
    
       // Creates a NamedRange that includes the new paragraph
       // Return the created Named Range
       var rangeBuilder = doc.newRange();
       rangeBuilder.addElement(text);
       return doc.addNamedRange(name, rangeBuilder.build()); 
    }
    
    
    function accessNamedRange(rangeId) { 
      // Determine if a NamedRange with this ID exists
      // If it does, log information about it and the Paragraph
      //   elements it includes
      var doc = DocumentApp.getActiveDocument();
      var named = doc.getNamedRangeById(rangeId);
      if (named) {
        var rangeElements = named.getRange().getRangeElements();
        for(var r in rangeElements) {
          var text = rangeElements[r].getElement().asParagraph().getText();
    
          // Just logging here, but could potentially edit or
          //   otherwise manipulate the text
          Logger.log('Found NamedRange ' + named.getName() +
            ' (id='+rangeId+') --> ' + text);
        }    
      }
    }