Google Apps Script docs.openById() not reopening document after saveAndClose() is called

Viewed 259

I am trying to use the method saveAndClose() to update the document. This script is bound to the document.

function one() {
    DocumentApp.getUi() // Or DocumentApp or FormApp.
        .alert('Some text.');
    var doc = DocumentApp.getActiveDocument();
    var body = doc.getBody();
    var text = body.editAsText();
    var id = doc.getId();
    virus = true;
    var warning = 'Some text.\n';
    var color = ['#ff0000','#000000','#0641a0'];
    var i;
    for (i = 0;i < 100; i++) {
        var doc = DocumentApp.openById(id);
        var j = i % 3;
        text.insertText(0, warning);
        text.setForegroundColor(0, warning.length - 1, color[j]);
        doc.saveAndClose();
    }
}

I don't know why it's not working. I keep getting the same error message:

Document is closed, its contents cannot be updated.

I thought I could reopen the document using DocumentApp.openById(id);, yet it doesn't work. If someone could help me, I would greatly appreciate it. Thanks!

0 Answers
Related