我有一个google脚本,用于从存储在google电子表格中的数据生成文档。文档生成后,我试图将所有者更改为不同的gmail帐户,但我一直得到以下错误:
[2015-09-23 09:55:09:480 PDT] File.setOwner([bob@gmail.com])[1.03秒]
[15-09-23 09:55:09:566 PDT]执行失败:Action not allowed(第82行,文件"Helpers"[5.401秒总运行时间]
我试图理解为什么我不能使用谷歌应用程序脚本更改所有者,但我可以手动通过谷歌驱动器。
细节:
Bob (Bob@gmail.com)与Alice (Alice@gmail.com)在他的驱动器上共享了一个目录。共享目录中有一个电子表格,用于从电子表格的内容生成发票。Alice使用电子表格(她有编辑权限)并调用"Generate>Invoice"菜单操作在电子表格上创建发票。由于她调用了该函数,因此创建的文件以Alice为所有者,但Bob希望成为所有发票的所有者。Bob试图在文档创建后使用Google App Script设置文档的所有者,但它返回了上面记录的错误。
电子表格内容:
| A | B |
1| First Name | Last Name |
2| John | Doe |
Google App Script:
/**
* Adds a menu-item to allow the generation of documents
*
* @param {Object} e The event parameter for a simple onOpen trigger.
*/
function onOpen(e) {
var menuitems = [];
menuitems.push({
name: "Invoice",
functionName: "createInvoice"
});
var ss = SpreadsheetApp.getActiveSpreadsheet();
ss.addMenu("Generate", menuitems);
}
/**
* This function reads data from cells A2:A3 to dynamically generate a document
*
*/
function createInvoice() {
var this_folder = cwd();
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
var content = sheet.getRange("A2:A3").getValues()[0].join(" ");
// Create a file with the given content
var file = DriveApp.createFile("Invoice", content);
// Add the file to the shared folder
this_folder.addFile(file);
// Remove the file from the user's root directory
DriveApp.getRootFolder().removeFile(file);
// Log the current owner of the document
Logger.log(file.getOwner().getName());
// Change the owner of the document from the active user to Bob.
file.setOwner("bob@gmail.com");
}
/**
* This is a helper function used to get the directory of the active spreadsheet.
*
*/
function cwd() {
var this_file = DriveApp.getFileById(SpreadsheetApp.getActive().getId());
return this_file.getParents().next();
}
复制步骤:
- 从一个gmail帐户,与另一个gmail帐户共享文件夹。
- 在主gmail帐户的共享文件夹中创建电子表格:
- 将Google App Script添加到电子表格中(将setOwner行更改为适当的电子邮件地址后)。
- 授予其他gmail帐户的写权限。
- 从另一个gmail帐户登录并加载文档。
- 调用脚本(生成>发票)。当你第一次这样做时,它会询问权限。
- 脚本应该出现以下错误:
不允许操作
- 如果你打开脚本并在调用脚本后查看日志,它将显示另一个gmail帐户拥有该文档,并且应该能够更改它。
附加信息:
- 如果我删除"file.setOwner()"方法创建文件,我可以通过web界面手动设置更改所有者。
- 使用脚本和设置,我已经动态创建文件夹,并能够使用谷歌应用程序脚本更改所有者。这个问题只出现在文件的setOwner()方法上。
从问题(强调我的)
Alice使用电子表格(她有编辑权限)并调用电子表格上的"Generate> Invoice"菜单操作来创建发票。由于她调用了该函数,因此创建的文件以Alice为所有者,但Bob希望成为所有发票的所有者。Bob试图在文档创建后使用Google App Script设置文档的所有者,但它返回上面记录的错误。
"Bob"不能转移文件的所有权,因为他不是文件的所有者。更简单的方法是请求"Alice",即文件的实际所有者,转移文件的所有权。
为了防止这个问题,"Bob"可以创建一个web应用程序,而不是使用自定义菜单,设置它作为他执行。
G Suite帐户的另一个替代方案是创建一个具有域范围授权的服务帐户,以模拟"Alice"来执行文件所有权的转移。有关详细信息,请参阅Peter Herman在Google Apps Script
当文件被放置在Google Drive的Team Drive文件夹中时,可能会发生此错误