如何在Google Apps Script添加记录后显示Bootstrap Toast弹窗4秒?
实现Google Apps Script添加记录后自动显示Bootstrap Toast弹窗
需求:调用Google Apps Script的addNewRow函数向表格添加记录成功后,自动触发Bootstrap Toast弹窗显示,持续4秒后自动隐藏。
1. 调整Toast组件代码
给Toast添加唯一ID,设置固定定位确保显示在页面右上角(可按需调整),保留Bootstrap无障碍属性:
<div class="toast" id="successToast" role="alert" aria-live="assertive" aria-atomic="true" style="position: fixed; top: 20px; right: 20px; z-index: 9999;"> <div class="toast-header"> <img src="..." class="rounded mr-2" alt="通知图标"> <strong class="mr-auto">操作成功</strong> <small>刚刚</small> <button type="button" class="ml-2 mb-1 close" data-dismiss="toast" aria-label="关闭"> <span aria-hidden="true">×</span> </button> </div> <div class="toast-body"> 记录已添加! </div> </div>
2. 确认Google Apps Script函数
保持原addNewRow函数逻辑不变,确保成功时返回true:
function addNewRow(rowData) { const currentDate = Utilities.formatDate(new Date(), "GMT+2", "dd.MM.yy"); const ss = SpreadsheetApp.getActiveSpreadsheet(); const ws = ss.getSheetByName('Data'); ws.appendRow([currentDate, rowData.docnumber1, rowData.whereandhow1, rowData.comment1, rowData.incomeeur1, rowData.incomeusd1, rowData.incomeuah1, rowData.eurrate1, rowData.usdrate1, rowData.expenseeur1, rowData.expenseusd1, rowData.expenseuah1, rowData.expensetype1]); return true; }
3. 前端触发逻辑
通过google.script.run调用Apps Script函数,在成功回调中初始化并显示Toast:
// 示例提交函数,需根据表单实际情况修改字段获取逻辑 function submitRecord() { // 收集表单数据组装rowData const rowData = { docnumber1: document.getElementById('docnumber1').value, whereandhow1: document.getElementById('whereandhow1').value, comment1: document.getElementById('comment1').value, incomeeur1: document.getElementById('incomeeur1').value, incomeusd1: document.getElementById('incomeusd1').value, incomeuah1: document.getElementById('incomeuah1').value, eurrate1: document.getElementById('eurrate1').value, usdrate1: document.getElementById('usdrate1').value, expenseeur1: document.getElementById('expenseeur1').value, expenseusd1: document.getElementById('expenseusd1').value, expenseuah1: document.getElementById('expenseuah1').value, expensetype1: document.getElementById('expensetype1').value }; // 调用Apps Script函数并处理结果 google.script.run .withSuccessHandler(function(isSuccess) { if (isSuccess) { // 初始化并显示Toast,设置4秒后自动隐藏 const toastEl = document.getElementById('successToast'); const toast = new bootstrap.Toast(toastEl, { delay: 4000 }); toast.show(); } }) .withFailureHandler(function(error) { console.error('添加记录失败:', error); // 可选:添加错误提示逻辑 }) .addNewRow(rowData); }
关键注意点
- 确保前端页面已正确引入Bootstrap的CSS、JS(Bootstrap 5+已集成Popper.js,无需额外引入)
- Toast组件默认处于隐藏状态,Bootstrap JS会自动处理显示/隐藏逻辑
- 可根据需求调整弹窗的
top、right定位值,避免被页面元素遮挡
内容的提问来源于stack exchange,提问作者Bohdan
相关产品推荐
相关产品推荐

