2014-09-25 86 views
2

我需要創建一個Google應用程序腳本,它將在活動文檔中插入一些字符串。 後來我需要知道用戶是否在文檔上使用了該腳本並更改了已插入的文本。將自定義屬性添加到Google文檔文本

是否可以標記或插入我添加的字符串的自定義屬性/屬性?

例如,而不是添加

<b>Custom Text</b> 

是否有可能插入這個?

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

另外,如何在文檔內搜索我的自定義屬性?

回答

2

您可以使用NamedRanges來實現此類效果。基本上,策略是:

  1. 添加你的文字,段落或其他文檔元素
  2. 裹在文檔NamedRange
  3. 記錄的NamedRange ID的文本,並將其與你需要的任何其他數據相關聯附加到特定的文本(例如插入時間或自定義屬性,或其他)。
  4. 稍後,當您需要查找文本(或只是確定它是否存在)時,可以查詢NamedRange ID的列表,然後使用該ID引用文檔中的文本。

這裏有一個粗略的實施這種戰略的:

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); 
    }  
    } 
}