Skip to content

Instantly share code, notes, and snippets.

@Max-Makhrov
Created February 16, 2022 13:09
Show Gist options
  • Save Max-Makhrov/e3e89e7fe0c6e86b68a4be1262e53629 to your computer and use it in GitHub Desktop.
Save Max-Makhrov/e3e89e7fe0c6e86b68a4be1262e53629 to your computer and use it in GitHub Desktop.
How to get active user email with installed onEdit trigger?
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('😎📬 run me 2x times')
.addItem('please let script to see your email', 'install')
.addToUi();
}
// function test() {
// var e = {
// range: SpreadsheetApp.getActive().getSheetByName('test_onEdit').getRange('B2')
// }
// edit_(e)
// }
function edit_(e) {
var targetcol = 1;
if (e.range.getSheet().getName() === 'Sheet1') {
var user = Session.getActiveUser().getEmail();
if (user !== '') {
var col = e.range.getColumn();
var rows = e.range.getHeight();
var ratgetrange = e.range.offset(
0,
targetcol - col,
rows,
1);
ratgetrange.setValue(user);
}
}
}
function install() {
setOnEditTrigger_(
SpreadsheetApp.getActive().getId(),
'edit_');
}
/**
* create onEdit trigger
*
* @param {string} spreadsheetId
* @param {string} functionName
*
*/
function setOnEditTrigger_(spreadsheetId, functionName) {
console.log('OnEdit trigger ' + functionName +
' for new file' +
spreadsheetId);
var trigger;
if (existsOnEditTrigger_(functionName, spreadsheetId)) {
console.log('stopped execution. Trigger exists.');
return;
}
trigger = ScriptApp
.newTrigger(functionName)
.forSpreadsheet(spreadsheetId)
.onEdit()
.create();
console.log('Created new trigger!')
return trigger.getUniqueId();
}
/**
* check if onEdit trigger exists
*
* @param {string} spreadsheetId
* @param {string} functionName
*
*/
function existsOnEditTrigger_(functionName, spreadsheetId) {
var triggers = ScriptApp.getProjectTriggers();
var trigger = {};
for (var i = 0; i < triggers.length; i++) {
trigger = triggers[i];
if (
trigger.getHandlerFunction() === functionName &&
trigger.getTriggerSourceId() === spreadsheetId &&
trigger.getEventType().toString() === 'ON_EDIT') return true;
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment