Closing Existing Sidebar using Google Apps Script

Gists

This is a sample script for closing the existing sidebar using Google Apps Script. When the sidebar is opened, in order to close the sidebar, the sidebar can be closed by running google.script.host.close() with the script of sidebar. This is the general case.

If you want to close the opened sidebar, such functions are not prepared. So I thought this workaround. The flow of this workaround is as follows.

Flow:

  1. Open a sidebar. Run run1_openSidebar().
    • At this time, an object {"sidebar": "open"} is put using PropertiesService.
  2. Close the sidebar. Run run2_closeSidebar().
    • When sidebar is open, this script is run.
    • In this case, the existing sidebar is overwritten by a temporal sidebar. 2 sidebars cannot be opened, simultaneously. This is the important point. By this, the sidebar can be closed by GAS.

Sample script:

In this script, the container-bound script of Spreadsheet is used as a sample.

function run1_openSidebar() {
  var p = PropertiesService.getScriptProperties();
  p.setProperty("sidebar", "open");
  var html = HtmlService.createHtmlOutput("sample sidebar");
  SpreadsheetApp.getUi().showSidebar(html);
}

function run2_closeSidebar() {
  var p = PropertiesService.getScriptProperties();
  if (p.getProperty("sidebar") == "open") {
    var html = HtmlService.createHtmlOutput("<script>google.script.host.close();</script>");
    SpreadsheetApp.getUi().showSidebar(html);
    p.setProperty("sidebar", "close");
  }
}

Note:

  • This sample script uses Spreadsheet. So if you want to use other Google Docs, please modify it.
  • This method can be also used for the custom dialog.
  • This workaround was answered at https://stackoverflow.com/a/54082847.

References:

 Share!