我需要创建一个google apps脚本,它会在活动文档中插入一些字符串。 我需要稍后知道用户是否在文档上使用了脚本并更改了已插入的文本。
是否可以为我要添加的字符串标记或插入自定义属性/属性?
例如,而不是添加
<b>Custom Text</b>
可以插入吗?
<p CustomAttribute=Cust1>Custom Text</p>
另外,如何在doc中搜索我的自定义属性?
答案 0 :(得分:3)
您可以使用NamedRanges实现此类效果。基本上,策略是:
以下是此类策略的粗略实施:
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);
}
}
}