【问题标题】:How to close parent window in an Apps Script Web App?如何在 Apps Script Web App 中关闭父窗口?
【发布时间】:2018-04-08 11:26:40
【问题描述】:

我在 Google Apps 脚本中有一个网络应用程序,我需要在单击按钮时关闭浏览器选项卡。我尝试了不同的解决方案,但它不能按我的要求工作。

这是我的 HTML 代码。

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <h1>Demo Close tab</h1>
    <p>When you click the button, you must close this tab.</p>
    <button>Close</button>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
    <script>
    window.onload = function() {
      $("button").click(function() {
        // window.close();
        // window.top.close();
        // window.open("","_top","").close();
      });
    }
    </script>
  </body>
</html>

这是我的 GS 代码

function doGet() {
  var template = HtmlService.createTemplateFromFile("Index");
  
  return template.evaluate()
  .setSandboxMode(HtmlService.SandboxMode.IFRAME)
  .addMetaTag("viewport", "width=device-width, initial-scale=1")
  .setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL)
  .setTitle("Demo Google Analytics");
}

【问题讨论】:

标签: google-apps-script web-applications sandbox


【解决方案1】:

如文档中所述HTML Service: Restrictions:

setSandboxMode 方法现在在调用时无效。

默认情况下,您的 Google Apps 脚本在 iframe 中运行,无论是否尝试更改沙盒模式。我强烈怀疑沙盒设置会阻止您访问父级window,但您可以尝试window.parent.window

【讨论】:

    【解决方案2】:

    根据 Javascript 文档: Window.close()

    这个方法只允许被脚本使用 window.open() 方法打开的窗口调用。如果窗口不是由脚本打开的,控制台会出现类似这样的错误:Scripts may not close windows that were not opened by script.

    【讨论】:

      【解决方案3】:

      Web 应用程序通常是 standalone script projects,根据 the documentationIFRAME 沙盒模式中应用的限制(即,截至 2021 年,only mode 可用),具有以下沙盒标志(对应于sandboxattribute) 设置在HTMLIFrameElement Web 应用程序中:

      Flag
      allow-same-origin
      allow-forms
      allow-scripts
      allow-popups
      allow-downloads
      allow-modals
      allow-popups-to-escape-sandbox
      allow-top-navigation-by-user-activation

      注意最后一个标志 - 这是当用户点击元素时能够启动导航但在调用 window.top.close()window.location.reload()window.location.replace(&lt;url&gt;) 等方法时不能启动导航的原因。


      这似乎直到 2021 年 9 月才对 bound 脚本项目严格执行,但现在是。截至目前,Issue Tracker 上有几个未解决的问题报告自动关闭的 Web 应用程序窗口停止工作 - 如果您想获取有关 Google 是否会重新考虑强制执行该标志的更新,请关注它们:

      【讨论】:

        猜你喜欢
        • 2023-03-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-10
        • 2012-12-15
        • 1970-01-01
        • 1970-01-01
        • 2023-03-20
        相关资源
        最近更新 更多