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 - 通过 Google Apps 脚本向 Discord channel 发送消息

javascript - 将同一 GAS 元素中的 CSS 和 JS 导入电子表格 HtmlOutput

javascript - 如何使用脚本同步谷歌日历和电子表格

google-sheets - 如何在公式中对零进行排序?

google-apps-script - Google Apps 脚本 - 获取包含特定值的单元格的行号

arrays - 从第一个空白开始计算单元格数量,并在下一个空白后重新开始计数

google-apps-script - 提交表单后获取事件电子表格行

javascript - Google Apps 脚本 - getRowIndex 无法正常工作

google-apps-script - Google Sheets 动态过滤可编辑数据

javascript - 从 localStorage 获取数据(谷歌脚本)