更新 Google Apps 脚本侧边栏中的内容而不重新加载侧边栏

Emp*_*yee 5 javascript google-apps-script

我使用以下 Google Apps 脚本代码在脚本运行时在电子表格的自定义侧边栏中显示内容:

function test() {

  var sidebarContent = '1<br>';

  updateSidebar(sidebarContent);

  sidebarContent += '2<br>';

  updateSidebar(sidebarContent);

  sidebarContent += '3';

  updateSidebar(sidebarContent);

}

function updateSidebar(content) {

  var html = HtmlService.createHtmlOutput(content)
      .setSandboxMode(HtmlService.SandboxMode.IFRAME)
      .setTitle('Sidebar')
      .setWidth(250);

  SpreadsheetApp.getUi().showSidebar(html);

}
Run Code Online (Sandbox Code Playgroud)

它可以工作,但是每次该updateSidebar()函数运行时,侧边栏都会在加载新内容时闪烁。

我该如何编程才能更有效地更新侧边栏的内容,从而消除闪烁?

我假设SpreadsheetApp.getUi().showSidebar(html);实际上应该只在开始时运行一次,并且内容的后续更新应该由 .js 文件中的 Javascript 处理。

但我不知道如何sidebarContent从用户浏览器中运行客户端的 JavaScript 代码获取变量。

另外,我知道这一定是可能的,因为我今天刚刚在 Google Apps 开发者博客上看到这篇关于使用自定义侧边栏的应用程序的帖子,并且文章末尾的 .gif 显示了一个正在更新的动画精美的侧边栏实时。

Jon*_*eed 4

我相信这种情况的解决方案是从客户端实际处理服务器端脚本的流程。这是我现在能想到的将数据从服务器传递到客户端而不重新生成 HTML 的唯一方法。
我的意思是,您希望从客户端调用服务器端函数,并让它们将响应作为成功处理程序返回给客户端。这意味着需要记录的每个操作都需要放入其自己的函数中。我将向您展示一个简单的例子来说明我的意思。假设您的服务器端 GAS 代码如下所示:

function actionOne(){
...insert code here...
return true;
}
function actionTwo(){
...insert code here... 
return true;
}
Run Code Online (Sandbox Code Playgroud)

依此类推,需要执行尽可能多的操作。

现在,对于您的 .html 文件,底部的 javascript 看起来像这样:

<script>
callActionOne();
function callActionOne(){
  google.script.run.withSuccessHandler(callActionTwo).actionOne();
}
function callActionTwo(){
...update html as necessary to indicate that the first action has completed...
google.script.run.withSuccessHandler(actionsComplete).actionTwo();
}
function actionsComplete(){
..update html to indicate script is complete...
}
</script>
Run Code Online (Sandbox Code Playgroud)

它比理想情况要复杂一些,您可能需要使用 CacheService 在操作之间存储一些数据,但它应该可以帮助您解决问题。如果您有任何疑问或这不符合您的需求,请告诉我。