更新:这是完全可能的。我只是在异步方法完成之前关闭主机窗口。我的解释是,即使 UI 关闭,运行上下文也会持续存在。不。
我想确认电子表格容器绑定(bind)项目中的 Apps 脚本函数是否可以通过 google.script.run 从 HTMLService 加载的 HTML 模板中的 JavaScript 函数调用。我的初步发现表明“不是”(见下文),但我可能遗漏了一些东西。
当在 onclick 处理程序调用的 JS 函数中进行 google.script.run 调用时,它会始终路由到错误处理函数,并显示以下错误代码:NetworkError: Connection failure due to HTTP 0.
如果我直接从按钮的 onclick 处理程序调用 google.script.run 代码,它就会运行。我希望能够在函数中使用它,以便我可以构建一组数据以传递到我计划实现的实际方法中。
我确实评论过this bug使用 Google 记录,但在这个简单的测试中我没有引用库。
这里有更多细节: - 新版本的工作表 - 使用最简单的代码创建新的电子表格和 AS 项目来重现问题。
我在容器绑定(bind)项目的应用程序脚本文件中有以下代码:
function onOpen()
{
var testMenu = SpreadsheetApp.getUi()
.createMenu('Custom Menu');
testMenu.addItem('Show UI in sidebar', 'showSidebar');
testMenu.addToUi();
};
function showSidebar(){
var html = HtmlService.createTemplateFromFile('simpleDialog');
SpreadsheetApp.getUi().showSidebar(html.evaluate());
}
function doWorkInAppsScriptFile()
{
Logger.log("doWorkInAppsScriptFile called.");
}
在“simpleDialog”html 文件(也在 Apps 脚本项目中)中,我有以下测试代码:
<h2>google script run test</h2>
<div style="width:98%;margin:10px">
<div style="width:98%;margin:10px;padding:10px;text-align:center">
<input type="button" id="saveButton" onclick="onSave()" value="Save" style="background:DarkGreen;color:White;font-weight:bold;margin:10px"/>
</div>
</div>
<script type="text/javascript">
function onSave(){
google.script.run.withFailureHandler(onFailure).doWorkInAppsScriptFile();
//Moving the following line to an onSuccess handler, and calling .withSuccessHandler,
// allows the code to close the window appropriately. Leaving this in causes the error discussed in this q.
google.script.host.close();
}
function onFailure(error)
{
alert("onFailure: " + error);
}
</script>
最佳答案
这里的罪魁祸首是 onSave()
函数中的这一行:
google.script.host.close();
删除/注释此行,脚本运行正常。您看到的错误是因为您用该行关闭了侧边栏,从而切断了与服务器端脚本的连接。
如果您确实需要在 onSave()
执行完成后关闭侧边栏,请将该行移至成功处理程序回调:
function onSave(){
google.script.run
.withSuccessHandler(onSuccess)
.withFailureHandler(onFailure)
.doWorkInAppsScriptFile();
}
function onSuccess(data)
{
// do something with returned data
// close the sidebar
google.script.host.close();
}
function onFailure(error)
{
alert("onFailure: " + error);
}
关于javascript - Apps 脚本 - 无法在 html 模板的 js 函数中使用 google.script.run?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27001676/