Home > Software engineering >  My Google Appscript is Not Working Because of the GetUser (I Guess...)
My Google Appscript is Not Working Because of the GetUser (I Guess...)

Time:08-16

function onEdit() {
  var sheet = SpreadsheetApp.getActive().getActiveSheet();
  var xCol = sheet.getActiveRange().getColumn();
  var xRow = sheet.getActiveRange().getRow();

  if ( xCol == 2 && sheet.getName() =='Çeviri' ) {
    var user = Session.getActiveUser().getUsername(); 
    sheet.getRange(xRow, 7).setValue(user); 
    }
  }

This script's purpose is; in Google Docs Excel, when a user change a cell in column B in sheet "Çeviri", it writes that users name 7 horizontal cells away. It's working though, in some way. When document's owner changes a cell in column B, app sees it and runs. But when another user changes a cell in column B, app doesn't see it and doesn't run. I think it's about Google, I guess they changed policies and because of that I can't get any other users name with this script https://developers.google.com/apps-script/reference/base/session#getuser

So my question is, is there any way to write this app without "getUser" command? Because I think it's the problem.

CodePudding user response:

In the general case, Google no longer allows scripts that run in an onEdit() context to find the identity of the user at the keyboard. From the documentation:

the user's email address is not available in any context that allows a script to run without that user's authorization, like a simple onOpen(e) or onEdit(e) trigger, a custom function in Google Sheets, or a web app deployed to "execute as me" (that is, authorized by the developer instead of the user). However, these restrictions generally do not apply if the developer runs the script themselves or belongs to the same G Workspace domain as the user.

In other words, if you are in a Google Workspace domain, you can discover the identity of the user at the keyboard and put their email address in a column.

It is best to ask users to authorize the script before running, which can be done with a custom menu item. See the insertActiveUserEmailAddressInColumn_ script for sample code.

CodePudding user response:

Try using it this way

function onMyEdit(e) {
  var sh = e.range.getSheet();
  if (e.range.columnStart == 2 && sh.getName() == 'Çeviri') {
    var user = Session.getActiveUser().getUsername();
    sh.getRange(e.range.rowStart, 7).setValue(user);
  }
}

    function creattrigger() {
      if (ScriptApp.getProjectTriggers().filter(t => t.getHandlerFunction() == "onMyEdit").length == 0) {
        ScriptApp.newTrigger("onMyEdit").forSpreadsheet(SpreadsheetApp.getActive()).onEdit().create();
      }
    }

Run the create trigger function. It's setup so that you can't create more than one.

  • Related