更新Google Apps Script侧边栏中的内容而无需重新加载侧边栏

Updating content in a Google Apps Script sidebar without reloading the sidebar

本文关键字:侧边栏 新加载 加载 Script Apps Google 更新      更新时间:2023-09-26

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

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);
}

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

我如何对其进行编程以更有效地更新侧边栏的内容,从而消除闪烁?

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

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

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

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

function actionOne(){
...insert code here...
return true;
}
function actionTwo(){
...insert code here... 
return true;
}

根据需要执行的操作数目依次类推。

现在,对于你的。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>

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