Hey everyone! I’m new to Google Apps Script and I’m trying to figure out how to keep some text in my document updated automatically. Here’s what I want to do:
I’ve got this line in my doc that says something like ‘Revision ID 123 - last updated Tue Aug 23 2022 10:30’. I want this to update every time the document is opened.
I know how to use replaceText()
for static placeholders, but that won’t work here because the text changes each time. Is there a way to target a specific part of the document reliably? Like, can I give a certain text field a name or ID that I can use to update it?
The reason I’m doing this is for PDF exports. I want readers to be able to check if they have the latest version.
Any ideas on how to make this work? Thanks for your help!
hey olivias! you could try using a Named Range for this. first, select the text u wanna update and give it a name (like ‘revisionInfo’). then in ur script, use DocumentApp.getActiveDocument().getNamedRanges(‘revisionInfo’)[0] to target it. this way u can update that specific part everytime the doc opens, no matter what the text is. hope this helps!
I’ve faced a similar challenge before, and here’s what worked for me: Use a combination of bookmarks and a custom onOpen() trigger. First, insert a bookmark at the location where you want the dynamic text. Then, create an onOpen() function that generates the new text (e.g., 'Revision ID ’ + Date.now() + ’ - last updated ’ + new Date().toLocaleString()) and replaces the content of the bookmark.
Here’s a rough outline of the script:
function onOpen() {
var doc = DocumentApp.getActiveDocument();
var bookmarks = doc.getBookmarks();
for (var i = 0; i < bookmarks.length; i++) {
if (bookmarks[i].getPosition().getElement().asText().getText() == 'REVISION_INFO') {
updateRevisionInfo(bookmarks[i]);
break;
}
}
}
function updateRevisionInfo(bookmark) {
var newText = 'Revision ID ' + Date.now() + ' - last updated ' + new Date().toLocaleString();
bookmark.getPosition().insertText(newText);
bookmark.remove();
DocumentApp.getActiveDocument().getBody().appendBookmark('REVISION_INFO');
}
This approach is reliable and doesn’t depend on the specific text content, making it perfect for your PDF export use case.
To accomplish this, you might consider utilizing a custom document property. One approach is to set up an onOpen() trigger for your document so that every time it is opened, a unique revision identifier is generated, for example using a timestamp.
The script would then store this identifier as a document property and use ContentService to insert a dynamic text field that fetches and displays the stored value. This method avoids the need to locate specific text and can be particularly useful for ensuring that exported PDFs always display the current version. It is advisable to test the solution thoroughly to confirm it meets your requirements.