You can check the execution transcript of your onOpen()
trigger function by opening the Script Editor shortly after opening the document, the selecting "View - Execution Transcript".
In there, you'll find something like this:
[13-08-01 11:53:18:163 EDT] Document.getName() [0 seconds]
[13-08-01 11:53:18:203 EDT] Execution failed: No item with the given ID could be found, or you do not have permission to access it. (line 41, file "Code") [0.052 seconds total runtime]
According to Understanding Triggers, simple triggers are not supposed to allow execution of services that require authentication. That restriction wouldn't seem to apply to Document.getName()
, especially after Document.getId()
has successfully worked. An issue exists for this, visit Issue 3083 and star it to vote & receive updates.
You'll find similar problems with your DocsList method calls, however they are not covered under the Google Apps Script Security Model, so it's not surprising that they get blocked.
As a work-around, you could have your onOpen()
remind the user to set the document variables, until they've done so.
function onOpen(e) {
DocumentApp.getUi().createMenu('Menu')
.addItem('Set variables', 'setVars')
.addToUi();
var doneFirstRun = ScriptProperties.getProperty('doneFirstRun');
if (doneFirstRun == null) {
var ui = DocumentApp.getUi();
ui.alert( "Set document variables\n\n"
+"Select Menu - Set variables");
}
}
function setVars() {
var ui = DocumentApp.getUi();
var document = DocumentApp.getActiveDocument();
var body = document.getBody();
var bodyText = body.editAsText();
var docID = document.getId();
var url = document.getUrl();
var docName = document.getName(); // Does not work in onOpen
var editors = document.getEditors(); // Does not work in onOpen
var viewers = document.getViewers(); // Does not work in onOpen
var file = DocsList.getFileById(docID);
var docCreated = file.getDateCreated().toString();
var docUpdated = file.getLastUpdated().toString();
// ... do actual work here
// Completed setting document variables - disable reminder.
var doneFirstRun = ScriptProperties.setProperty('doneFirstRun',true);
ui.alert("Completed");
}