google-apps-script - 确定 Apps 脚本中的当前用户

标签 google-apps-script google-sheets

我正在尝试识别当前用户的名称,以记录谁编辑了如下内容:

  r.setComment("Edit at " + (new Date()) + " by " + Session.getActiveUser().getEmail());

但它不起作用 - 用户名是空字符串。 我哪里出错了?

最佳答案

好消息:通过这个解决方法是可能的!

我正在使用一些保护功能来显示文档的用户和所有者,并将其存储在属性中以获得更好的性能。玩得开心!

function onEdit(e) {
  SpreadsheetApp.getUi().alert("User Email is " + getUserEmail());
}

function getUserEmail() {
  var userEmail = PropertiesService.getUserProperties().getProperty("userEmail");
  if(!userEmail) {
    var protection = SpreadsheetApp.getActive().getRange("A1").protect();
    // tric: the owner and user can not be removed
    protection.removeEditors(protection.getEditors());
    var editors = protection.getEditors();
    if(editors.length === 2) {
      var owner = SpreadsheetApp.getActive().getOwner();
      editors.splice(editors.indexOf(owner),1); // remove owner, take the user
    }
    userEmail = editors[0];
    protection.remove();
    // saving for better performance next run
    PropertiesService.getUserProperties().setProperty("userEmail",userEmail);
  }
  return userEmail;
}

关于google-apps-script - 确定 Apps 脚本中的当前用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12300777/

相关文章:

javascript - 将日期/时间设置为 00 :00:00

csv - 将未发布的Google电子表格下载为CSV

google-apps-script - GAS 中的脚本和自定义函数有什么区别?

colors - 以编程方式在电子表格中设置边框颜色和样式

javascript - 使用 Google 电子表格中的 onEdit 实时编辑单元格内容

javascript - 如何使用负时间戳进行数学运算?

excel - 将预览悬停在 Excel 图像链接上

Azure SQL : Cannot connect via JDBC from Google Sheets

google-apps-script - 用于从 Google 文档中删除多余空格的 Google Apps 脚本

google-apps-script - 从谷歌应用程序脚本预填谷歌表单