google-apps-script - Apps 脚本 - 如何检测对话框是否关闭

标签 google-apps-script google-apps-script-addon

我需要检测 Apps 脚本中对话框何时关闭(当用户单击对话框右上角的 X 按钮时)

这个方法我试过了,还是不行

window.addEventListener('beforeunload', function (e) {
    e.preventDefault();
    google.script.host.close()
});

那怎么办呢?谢谢。

最佳答案

  • 您的问题涉及 custom modal dialog 的关闭
  • 这种对话框在脚本的 html 部分定义并在客户端运行
  • 这意味着要检测此类对话框的关闭,您需要实现客户端事件监听器 - 即 Javascript 方法
  • 一种可能是使用 window event handler与事件 window.unload

示例:

Code.gs

function onOpen() {
  SpreadsheetApp.getUi() // Or DocumentApp or SlidesApp or FormApp.
      .createMenu('Custom Menu')
      .addItem('Show dialog', 'showDialog')
      .addToUi();
}

function showDialog() {
  var html = HtmlService.createHtmlOutputFromFile('index')
      .setWidth(400)
      .setHeight(300);
  SpreadsheetApp.getUi() // Or DocumentApp or SlidesApp or FormApp.
      .showModalDialog(html, 'My custom dialog');
}

index.html

<html>
  <head>
    <base target="_top">
  </head>
  <body>
  Hello, world! <input type="button" value="Close" onclick="google.script.host.close()" />
 <script> 
 window.addEventListener("unload", function() {console.log("It works"); });
 </script>
  </body>
</html>

Note: The event listener in the sample will notice when the user closes the dialog, however it cannot detect the difference between closing by pressing the X and pressing the CLOSE button.

关于google-apps-script - Apps 脚本 - 如何检测对话框是否关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59485690/

相关文章:

google-apps-script - 比较两个电子表格并使用谷歌应用程序脚本输出差异

google-apps-script - 注销后清除导航堆栈 - Gmail 插件

google-apps-script - 如何在谷歌文档插件中的文本悬停上显示图像

google-apps-script - 如何使用 Google Apps Script 或 API 判断 Google 幻灯片中的幻灯片是否为 "skipped"?

google-apps-script - 使用我自己的 Google Docs 插件而不发布它

javascript - Google 应用程序脚本无法识别基于 Chromium 的 Edge

google-apps-script - 如何使用 UrlFetchApp 为 BigQuery Rest API 添加媒体上传?

javascript - Google Apps 表格跳过 if 语句

javascript - 使用 Google Apps 脚本获取 gmail 地址,错误 : redirect_uri_mismatch

javascript - 在 Google 表格中输入数据后自动保护单元格/范围