onOpen-function doesn't work correct

2019-09-05 21:40发布

问题:

Script-Editor: wrote a script with the onOpen-function (see below). When started with the script-editor, it works correctly. when started when the spreadsheet is opened, I get the log of stmt 31 "Logger.log(name)", nothing else happens. Why?

Here is the complete script:

function onOpen() {
  n0="T22 ";
  n1=n0+"aktuell"
  n2=n0+"Master"
  var y1=DayShift();
  Browser.msgBox("Returned with "+y1);
};

function DayShift() { 
  var dt=Browser.inputBox("Datum (YYMMDD) eingeben");
  if (dt=="cancel" || dt.length !=6) return("Input "+dt);

  var f1=GetFL(n1,0);
  if (f1=="cancel") return("F1 cancel");
  Logger.log(f1);
  var Rx=f1.getSheetByName("Sheet1").getRange("B9").getValue();
  f1.rename(n0+dt);
  Logger.log(Rx);
  Logger.log(f1.getName()+" finished");

  var f2=GetFL(n2,1);
  if (f2=="cancel") return("F2 cancel");
  Logger.log(f2);
  f2.getSheetByName("Sheet1").getRange("B7").setValue(Rx);
  Logger.log(f1.getName()+" finished");

  return("OK");
};

function GetFL(name,typ) {
  Logger.log(name);
  var fx = DocsList.find(name);
  Logger.log(name+" = "+fx.length);
  if (fx.length != 1)  return("cancel");
  if (typ==1) {
    var fy=fx[0].makeCopy(n1);
  } else {
    var fy=fx[0];
  };
  fy=SpreadsheetApp.openById(fy.getId());
  Logger.log(fy);
  return (fy);
};

回答1:

running onOpen from the script editor treats as any other script. running it as a simple triggered function will not allow access to the DocsList API as this cannot be run anonymously. Even if you have authorised the script to run as you, simple triggers run anonymously and certain APIs will not allow this.

In this case onOpen (and onEdit) silently fail.

It won't fix this for you, but the explanation can be found in the GAS documentation.

It can be frustrating/mystifying when you first encounter this, but there are ways around it even if it means running scripts from menu commands or buttons: both confer identity of the user on the script.



回答2:

As a complement to Jonathon's answer, you could use the installable onOpen trigger instead of the simple one. Just give this function another name to avoid confusion, for example IonOpen() or whatever... the installable triggers don't have the limitations Jonathon was mentioning. See doc on Using Container-Specific Installable Triggers