且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我可以阻止具有编辑权限的人修改我的Google Apps脚本吗?

更新时间:2023-12-05 23:16:46

通过创建未绑定脚本并调用以下全局变量来隔离代码:

Isolate the code by creating an unbound script and calling the following global variables:

var ss = SpreadsheetApp.openById("yourSheetIdHere");
var sheet = ss.getSheetByName("sheetName");
/* do more stuff */

这样,您是唯一运行脚本发送电子邮件的用户.当该脚本解除绑定时,它始终以您的身份运行,并且没有编辑权限的人无法打开该脚本.不过,您需要创建一个可以监视工作表的触发器. 来自Google Apps文档:

This way, you're the only user running the script to send the email. When the script is unbound, it always runs as you and cannot be opened by someone without edit rights. You'll need to create a trigger which watches the sheet, though. From the Google Apps docs:

function createSpreadsheetEditTrigger() {
  var ss = SpreadsheetApp.getActive();
  ScriptApp.newTrigger('myFunction')
      .forSpreadsheet(ss)
      .onEdit()
      .create();
}

然后,要确保没有人弄乱您的电子邮件,您可以选择两条路线中的一条,都使用Session.getActiveUser().

Then, to be super-sure no one is messing with your emails, you could take one of a couple routes, both using Session.getActiveUser().

方法一-以活动用户身份发送电子邮件.

Method One - Send email as the active user.

这很简单-使用Session.getActiveUser().getEmail()设置一个email变量,并将其传递到您的GmailApp方法中.这将设置要从图纸编辑器发送的电子邮件地址.

This is simple - set an email variable with Session.getActiveUser().getEmail() and pass that into your GmailApp method. This will set the email address to send from the sheet editor.

方法二-验证试图运行该功能的用户.

Method Two - Validate the user trying to run the function.

您还可以将经过身份验证的用户存储在脚本的数组中.使用Session.getActiveUser().getEmail()并检查数组是否包含电子邮件地址.如果是这样,请从身份验证器功能中选择return true并继续.如果没有,请传递错误消息.

You could also store authenticated users in an array in your script. Use Session.getActiveUser().getEmail() and check that the array contains the email address. If so, return true from the authenticator function and continue. If not, pass an error message.

此处是Google文档