HtmlService模态框调用SwitchToSheet1函数失效问题
问题:HtmlService模态对话框5秒后切换工作表失败
我尝试在HtmlService模态对话框打开5秒后切换当前工作表,但SwitchToSheet1()函数无法正常工作。相关代码如下:
.gs 代码
function openModal() { var ui = SpreadsheetApp.getUi(); var html = HtmlService.createTemplateFromFile('BarcodeLoadingHTML') .evaluate() .setWidth(400) .setHeight(250); ui.showModalDialog(html, ""); } function SwitchToSheet1() { var spreadsheet = SpreadsheetApp.getActiveSpreadsheet(); spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Bestandsliste'), true); };
BarcodeLoadingHTML.html 代码
<!DOCTYPE html> <html> <head> <base target="_top"> <?!= include('jQuery'); ?> <?!= include('Stylesheet'); ?> <?!= include('lottieplayer'); ?> </head> <body> <div id="loading"> <lottie-player id="lottie-load" src="https://static.staticsave.com/lottie/cloudupload.json" background="transparent" speed="1" loop autoplay> </lottie-player> <lottie-player id="lottie-success" src="https://assets3.lottiefiles.com/private_files/lf30_qXYuJE.json" background="transparent" speed="1"> </lottie-player> <p class="loadingtext" id="text">Bitte warten<span>.</span><span>.</span><span>.</span></p> </div> <script> $(window).ready(setTimeout (function() { $('#lottie-load').hide() $('#text').text('Upload Erfolgreich!') $('#lottie-success').fadeIn() $('#lottie-success').get(0).play(); }, 2500)); $(window).ready(setTimeout (function() { google.script.run.SwitchToSheet1(); google.script.host.close(); }, 5000)); </script> </body> </html>
解决方案
问题根源
- 异步执行被中断:
google.script.run是异步调用服务端函数,调用后立刻执行google.script.host.close()会终止未完成的服务端请求,导致切换工作表的操作被中断。 - 事件绑定错误:
$(window).ready(setTimeout(...))写法不正确,ready方法需要接收函数,直接传入定时器ID无法正确绑定就绪事件。
修改步骤
- 修正
$(window).ready的写法,将定时器放在就绪事件的回调函数内。 - 使用
google.script.run的withSuccessHandler方法,确保切换工作表成功后再关闭对话框。
修改后的HTML脚本代码
$(window).ready(function() { // 2.5秒后切换动画和文本 setTimeout(function() { $('#lottie-load').hide(); $('#text').text('Upload Erfolgreich!'); $('#lottie-success').fadeIn(); $('#lottie-success').get(0).play(); }, 2500); // 5秒后调用切换工作表函数,成功后关闭对话框 setTimeout(function() { google.script.run .withSuccessHandler(function() { google.script.host.close(); }) .SwitchToSheet1(); }, 5000); });
额外检查点
- 确认工作表名称
Bestandsliste拼写完全正确,且该工作表确实存在于当前电子表格中。 - 确保当前用户拥有操作该电子表格的权限,能够切换工作表。
内容的提问来源于stack exchange,提问作者Rookie_Js
相关产品推荐
相关产品推荐

