[英]Google Script HTML form from Library throws error Uncaught
我有一个像这样的 HTML 格式的库:
code.gs
:
function openDialog() {
SpreadsheetApp.getUi().showModalDialog(HtmlService.createHtmlOutputFromFile("h"), "Test" );
}
function hello() {
console.log('booo');
}
h.html
:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<button id="b">Click me</button>
<script>
var b = document.getElementById('b');
b.onclick = function() {
google.script.run
.withSuccessHandler(function(str){window.alert("executed");})
// .withFailureHandler(function(error){window.alert("failed");})
.hello();
}
</script>
</body>
</html>
我共享了这个脚本以供查看并将其部署为库。 接下来,我使用以下代码在 Google Sheet 中创建了一个绑定脚本:
function onOpen() {
SpreadsheetApp.getUi().createMenu('test').addItem('run', 'myFunction').addToUi();
}
var hello = function() {};
function myFunction() {
TT.openDialog();
}
我添加了带有标识符的库:TT。
接下来,我使用绑定代码刷新了我的 Google 表格文件以查看菜单“测试”,运行测试 > 运行。 HTML 窗口出现了。 当我点击按钮时,什么也没发生。 当我打开控制台时,我看到了错误:
如果我不使用库,则不会出现此错误。
请帮我解决这个问题。
我和你经历过同样的情况。 就我而言,问题的原因是图书馆方面的授权。
Uncaught
的错误。Uncaught
的错误。也就是说,在我的环境中,我确认当库用于您的情况时,需要为客户端和库端授权范围。
因此,作为一种解决方法,我使用了以下流程。
code.gs
和h.html
脚本复制并粘贴到独立脚本或容器绑定脚本。hello()
并授权范围。myFunction()
。 通过此流程,当您在自定义菜单上运行run
并单击按钮时,将打开executed
对话框。
作为从客户端授权库端范围的方法,我想建议使用 Web 应用程序。 我以为在使用Web Apps时,库端的授权可以在客户端完成。 至此,我认为不便之处可能会得到一点解决。
请执行以下流程。
请复制并粘贴以下脚本。
code.gs
function openDialog() {
SpreadsheetApp.getUi().showModalDialog(HtmlService.createHtmlOutputFromFile("h"), "Test" );
}
function hello() {
console.log('booo');
}
function doGet() {
return HtmlService.createHtmlOutput("ok");
}
h.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<button id="b">Click me</button>
<script>
var b = document.getElementById('b');
b.onclick = function() {
google.script.run
.withSuccessHandler(function(str){window.alert("executed");})
// .withFailureHandler(function(error){window.alert("failed");})
.hello();
}
</script>
</body>
</html>
请在库侧部署 Web 应用程序。 关于这个方法,可以看官方文档。 参考详细设置如下。
Execute as: User accessing the web app
Who has access: Anyone with Google account
请部署为库。 参考
请将库安装到客户端。 并且,请复制并粘贴以下脚本。 在这种情况下,请将https://script.google.com/macros/s/###/exec
替换为您的 Web 应用程序 URL。
function onOpen() {
SpreadsheetApp.getUi().createMenu('test').addItem('auth', 'auth').addItem('run', 'myFunction').addToUi();
}
var hello = function() {};
function myFunction() {
TT.openDialog();
}
function auth() {
const html = HtmlService.createHtmlOutput(`<input type="button" value="Authorize" onclick="window.open('https://script.google.com/macros/s/###/exec', '_blank');google.script.host.close()">`);
SpreadsheetApp.getUi().showDialog(html);
}
首先,请在自定义菜单中运行auth
。 这样,您可以授权客户端和库端的范围。 如果运行auth
时没有打开新选项卡,请在脚本编辑器中再次运行auth()
。
作为下一步,请运行run
。 这样,您的对话框就打开了。 并且,当两个auth
(客户端和库端)都已经完成时,当您单击按钮时,将打开executed
对话框。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.