当SpreadSheet被另一个脚本更改时,Google Apps脚本会运行

时间:2013-06-28 06:47:37

标签: google-apps-script real-time google-sheets onchange

我正在尝试使用UiApp编写一个在SpreadSheet文件中显示行值的脚本。

每当SpreadSheet发生变化时,此脚本都需要更新数据。只需触发onChange,这通常很简单。

但是,SpreadSheet本身也会被另一个函数更新,并且当所做的更改是由另一个AppScript引起时,似乎不会触发onChange。

有没有其他方法可以实现我所描述的目标?

下面的代码,谢谢

    var ss = SpreadsheetApp.openById("tqwJk280I1O_yW5oNX9nLQA");

function doGet() {
  var app = UiApp.createApplication();
  var masPanel = app.createFlowPanel().setId("panel");
  var number = parseInt(ss.getRange("A1").getValue());
  masPanel.add(app.createLabel(number));
  masPanel.add(app.createFlowPanel().add(app.createFormPanel()
           .add(app.createFlowPanel()
           .add(app.createSubmitButton("Plus!")))));

  app.add(masPanel);

  return app;
}

function doPost()
{
  var num = parseInt(ss.getRange("A1").getValue()) + 1;
  ss.getRange("A1").setValue(num);
}

function onChange()
{
  ss.getRange("A2").setValue("hahaha");
  var app = UiApp.createApplication();
  app.remove(app.getElementById("panel"))
  var masPanel = app.createFlowPanel().setId("panel");
  var number = parseInt(ss.getRange("A1").getValue());
  masPanel.add(app.createLabel(number));
  masPanel.add(app.createFlowPanel().add(app.createFormPanel()
           .add(app.createFlowPanel()
           .add(app.createSubmitButton("Plus!")))));

  app.add(masPanel);

  return app;
}

1 个答案:

答案 0 :(得分:2)

onChange()函数不会引用UI。例如,如果有多个人打开了相同的UI,哪一个应该更新?

因此,问题的解决方案是让您的UI代码定期轮询电子表格,并在电子表格发生变化时更新UI。为此,您可以使用未记录的addTimer()方法。 请参阅此SO question & answer以获取一个很好的示例