[英]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.