2012-09-06 51 views
5

確定當前用戶我想,以確定當前用戶的名稱,以使誰編輯什麼像這樣的註釋:應用腳本

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

,但它不會工作 - 用戶的姓名爲空字符串。 我哪裏錯了?

+0

請檢查此[文章](http://stackoverflow.com/questions/12172849/how-to-indentify-user-using-google-apps-script/)。你的腳本可能有同樣的問題。 – megabyte1024

+0

http://stackoverflow.com/questions/12172849/how-to-indentify-user-using-google-apps-script/檢查這個答案....你會得到的想法 –

回答

4

我假設你有這片設置爲onEdit函數中執行代碼(或在編輯觸發器)。

如果你是一個消費者賬戶,Session.getActiveUser)().getEmail()將返回空白。只有當腳本的作者和用戶都在同一個Google Apps域中時,它纔會返回電子郵件地址。

+0

如果安全策略不允許訪問用戶的身份,User.getEmail()返回一個空白字符串。電子郵件地址可用的情況會有所不同:例如,用戶的電子郵件地址在任何允許腳本在沒有該用戶授權的情況下運行的情況下都不可用,如簡單的onOpen(e)或onEdit(e)觸發器, Google Sheets中的自定義功能或部署爲「作爲我執行」(即由開發人員而非用戶授權)的Web應用程序。 https://developers.google.com/apps-script/reference/base/session –

5

好消息:有可能與此解決辦法!

我使用的顯示文檔的用戶和所有者一定的保護功能,我將其存儲在性能獲得更好的性能。玩得開心!

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; 
} 
-1
function onEdit(e) { 
    SpreadsheetApp.getUi().alert("User Email is " + e.user); 
}