【发布时间】: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 在工作表中更改选择时自动调用。
我相信这是对插件开发的普遍需求。那么有谁知道如何让onSelectionChange 的code.gs 通知onSelectionChangeJs 的index.html?
【问题讨论】:
-
onSelectionChange 触发器仅触发此函数
function onSelectionChange(e) { Logger.log("Selection changed "); }您必须将该事件保存在某处,并且您的 javascript 必须轮询它。 -
除了轮询还有其他解决方案吗?理想情况下,我想首先从 fontend 生成事件(当用户单击单元格时)
-
那么您的 javascript 在您的浏览器上运行并且触发器在服务器上触发。因此,除非您知道服务器在浏览器不请求的情况下向浏览器发送数据的方法,否则我会拒绝。
-
是的,我知道这一点。但是该事件最初是由例如 mouseClick 在前端触发的。为什么不传给服务器就不能直接抓到。
-
正如库珀所说 - 在您的情况下,轮询是唯一的选择。您可以以高频率拉动活动单元格,这将创建“几乎直接”的更新。鉴于
onSelection()是simple trigger,它不允许您创建新的html 输出或调用Webapp。根据您的情况,也许您可以使用onEdit()触发器找到解决方案?后者是可安装的,因此限制较少。
标签: google-apps-script google-sheets