【问题标题】:Catching onSelectionChange in the frontend side for a Google Sheets add-on在 Google 表格插件的前端捕获 onSelectionChange
【发布时间】:2021-08-17 07:43:30
【问题描述】:

在 Google 表格中,我有一个插件,它由后端 code.gs 和前端 index.html 两部分组成,其中 index.html 是在单击菜单时显示的侧边栏。 这里是code.gs

function onOpen() {
  SpreadsheetApp.getUi()
    .createMenu('My add-on')
    .addItem('Test', 'openSideBar')    
    .addToUi();
}

function onSelectionChange(e) {
  Logger.log("Selection changed ");     
}

function openSideBar() {
  var html = HtmlService.createHtmlOutputFromFile('Index');
  SpreadsheetApp.getUi().showSidebar(html);
}

function getCurrentSelection() {
  var currentCell = SpreadsheetApp.getCurrentCell();

  return { column: currentCell.getColumn(), row: currentCell.getRow() };
}

这是onSelectionChange 的文档。 Logger.log("Selection changed") 确实在选择更改时被调用。但是,当用户单击单元格并更改选择时,我需要在前端通知或进行更改。

这里是index.html

<!DOCTYPE html>
<html>
<head>
    <base target="_top">
</head>
<body>
    Test
    <input type="text" id="formula" />
    <script>
      function onSelectionChangeJs(e) {
        document.getElementById("formula").value = e ; 
      }

      function loadCell() {
        google.script.run.withSuccessHandler(onSelectionChangeJs).getCurrentSelection(); 
      }
    </script>
    <button onclick="loadCell()">Get cell</button>
</body>
</html>

虽然目前我在单击按钮时检查当前选择,但我需要 onSelectionChangeJs 在工作表中更改选择时自动调用。

我相信这是对插件开发的普遍需求。那么有谁知道如何让onSelectionChangecode.gs 通知onSelectionChangeJsindex.html

【问题讨论】:

  • onSelectionChange 触发器仅触发此函数function onSelectionChange(e) { Logger.log("Selection changed "); } 您必须将该事件保存在某处,并且您的 javascript 必须轮询它。
  • 除了轮询还有其他解决方案吗?理想情况下,我想首先从 fontend 生成事件(当用户单击单元格时)
  • 那么您的 javascript 在您的浏览器上运行并且触发器在服务器上触发。因此,除非您知道服务器在浏览器不请求的情况下向浏览器发送数据的方法,否则我会拒绝。
  • 是的,我知道这一点。但是该事件最初是由例如 mouseClick 在前端触发的。为什么不传给服务器就不能直接抓到。
  • 正如库珀所说 - 在您的情况下,轮询是唯一的选择。您可以以高频率拉动活动单元格,这将创建“几乎直接”的更新。鉴于onSelection()simple trigger,它不允许您创建新的html 输出或调用Webapp。根据您的情况,也许您可​​以使用onEdit() 触发器找到解决方案?后者是可安装的,因此限制较少。

标签: google-apps-script google-sheets


【解决方案1】:

听起来好像当用户更改表格中的单元格时,您希望该更改反映在 HTML 页面中,对吧? 您不将该值发送到 HTML 吗?我认为这需要刷新 HTML 页面,但您可以使用该新参数进行重建。我对附加组件的了解还不够多。 但是,如果您有一个 onSelectionChange() 仅触发 Logger.log。它可以触发一个函数,该函数使用插入到 html id“公式”中的 e 来刷新 HTML。 不能直接用代码改js,但是可以写code.gs做和html js一样的事情。 这是你需要的方向吗?

【讨论】:

  • 其实这就是我首先尝试的。但谷歌禁止在OnEditonSelectionChange等事件上显示侧边栏。虽然创建自定义触发器可以解决onEdit 的问题,但不能解决onSelectionChange 的问题。无论如何,在 onSelectionChange 上刷新整个 html 是不利的,此外在服务器操作和工作表响应之间有很长的时间。在问题跟踪器中引用谷歌团队:issuetracker.google.com/issues/69238694#comment38
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-03
  • 1970-01-01
  • 2017-04-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多