在 Apps 脚本中确定当前用户 [英] Determine current user in Apps Script

查看:25
本文介绍了在 Apps 脚本中确定当前用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试识别当前用户的姓名以记录谁编辑了这样的内容:

I'm trying to identify current user's name to make notes of who edited what like this:

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

但它不起作用 - 用户名是一个空字符串.我哪里做错了?

but it won't work - user's name is an empty string. Where did I go wrong?

推荐答案

好消息:这个解决方法是可行的!

GOOD NEWS: It's possible with this workaround!

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

I'm using some protection functionality that reveals the user and owner of the document and I'm storing it in the properties for better performance. Have fun with it!

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;
}

这篇关于在 Apps 脚本中确定当前用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆