Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Sheet Add-on get user email

I have an Google Sheet add-on published in the store. But I can't get the user email back.

On Code.js, onStartup() when the app(sidebar) is loaded on the screen.

function onStartup() {
  return Session.getActiveUser().getEmail();
}

On my client side javascript, this is how I invoke onStartup().

google.script.run
        .withSuccessHandler(
          function(ret, scope) {
            console.log(">>> user email is: " + ret);
          })
        .withFailureHandler(
          function(msg, scope) {
          })
        .withUserObject()
        .onStartup();

EDIT:

Try getEffectiveUser() if you're working on an Add-on.

like image 572
angelokh Avatar asked Nov 01 '25 02:11

angelokh


1 Answers

This worked in my test, it did initially give me some issues for an unknown reason:

Example: https://docs.google.com/spreadsheets/d/1zevasz5XjumO92qOwYIvsqoUPkzyB9EBD27pWH2I5e0/copy

code.gs

function onOpen() {
  var ui = SpreadsheetApp.getUi()
  var menu = ui.createAddonMenu().addItem('Launch Sidebar', 'sidebar').addToUi();
}

function sidebar(){
   var ui = SpreadsheetApp.getUi();
  var html = HtmlService.createHtmlOutputFromFile("Sidebar.html")
  .setSandboxMode(HtmlService.SandboxMode.IFRAME)
  .setTitle("Sidebar Listbox");
  ui.showSidebar(html);
}

function getListItems(){
  var activeUser = "Active User";
  var effectiveUser = "Effective User";
  try{
    activeUser = Session.getActiveUser().getEmail();
  } catch(err1){
    activeUser = err1;
  }
  try{
    effectiveUser = Session.getEffectiveUser().getEmail();
  } catch(err2){
    effectiveUser = err2; 
  }
  var returnArray = [activeUser,effectiveUser]; 
  return returnArray;
}

Sidebar.html

  <link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">

<p>
Effective User: <span id="effectiveUser"></span>
</p>
<p>
Active User: <span id="activeUser"></span>
</p>


  <script src="//code.jquery.com/jquery-1.10.2.js"></script>
  <script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>

  <script>
  $(function() {    //This function runs automatically when the sidebar is opended  
        google.script.run.withSuccessHandler(loadListItems).withFailureHandler(fail).getListItems();
  });


    function loadListItems(returnedData){
    $( "#effectiveUser" ).html(returnedData[0]);
    $( "#activeUser" ).html(returnedData[1]);   
  }
     function fail(){
        //update the field with the id of yourChoice
      $( "#effectiveUser").html("<strong> Opps, something went wrong.... </strong>");
  }
  </script>
like image 128
Bjorn Behrendt Avatar answered Nov 04 '25 08:11

Bjorn Behrendt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!